4Sum

To solve this coding challenge, we need to find all unique quadruplets in a given array that sum up to a specific target. The quadruplets must be distinct, meaning none of the indices in any of the quadruplets should be the same. We'll leverage a recursive approach to break down the problem into more manageable sub-problems, eventually utilizing a two-pointer technique for the base case.

# Explanation:

  • We utilize a recursive function
    findNsum
    to reduce the N-sum problem into smaller problems until we reach the 2-sum problem.
  • First, we sort the array
    nums
    to facilitate the two-pointer technique for the 2-sum problem.
  • The
    findNsum
    function works as follows:
    • Base case: If
      N
      equals 2 (i.e., looking for pairs), use a two-pointer technique to find pairs that sum up to the reduced target.
    • Recursive case: For
      N > 2
      , loop through the array, and recursively reduce the problem to an (N-1)-sum problem while adjusting the target accordingly.
  • To ensure uniqueness, skip the elements that are the same as the previous one during iteration.
  • The main function initializes the recursion and sorts the result before returning it.

# Detailed Steps in Pseudocode:

  1. Sort the array : Sorting helps to use the two-pointer technique effectively.
  2. Recursive function : Define a recursive function
    findNsum
    .
    • Parameters : Input array
      nums
      , current target
      current_target
      , integer
      N
      (indicating the N-sum problem),
      current_result
      (stores the current quadruplet being constructed), and
      all_results
      (stores all valid quadruplets).
  3. Base case for recursion :
    • If
      N
      is 2, use two pointers (
      left
      and
      right
      ) to find pairs that sum up to
      current_target
      .
    • Adjust pointers and skip duplicates.
  4. Recursive case :
    • Iterate through the array, recursively call
      findNsum
      to reduce the problem to (N-1)-sum, and adjust the target by subtracting the current element.
  5. Initialize and call the recursion : Call
    findNsum
    from the main function with initial parameters.
  6. Return results : Return the list of unique quadruplets.

# Pseudocode:

                                            
# Function to find N unique numbers summing to target

def findNsum(nums, current_target, N, current_result, all_results):
    # if the length of nums is less than N or impossible to find a sum based on boundary conditions, return
    if len(nums) < N or N < 2 or current_target < nums[0] * N or current_target > nums[-1] * N:
        return
    
    # Base case: If looking for pairs (N == 2)
    if N == 2:
        left, right = 0, len(nums) - 1
        
        # Two-pointer technique to find pairs 
        while left < right:
            current_sum = nums[left] + nums[right]
            
            # Check if current pair sums to the target
            if current_sum == current_target:
                # Add found pair to results
                all_results.append(current_result + [nums[left], nums[right]])
                left += 1
                # Skip duplicates
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
            elif current_sum < current_target:
                left += 1
            else:
                right -= 1
                
    else:
        # Recursive reduction for N-sum problem
        for i in range(len(nums) - N + 1):
            # Avoid duplicate results by skipping duplicates
            if i == 0 or (i > 0 and nums[i] != nums[i - 1]):
                # Recursively reduce the problem to an (N-1)-sum problem
                findNsum(nums[i + 1:], current_target - nums[i], N - 1, current_result + [nums[i]], all_results)


# Main function to find all unique quadruplets
def fourSum(nums, target):
    all_results = []  # List to store all unique quadruplets
    nums.sort()       # Sort the array to facilitate the two-pointer approach for the 2-sum problem
    findNsum(nums, target, 4, [], all_results)  # Start the recursion for 4-sum
    return all_results

# Example usage:
# print(fourSum([1, 0, -1, 0, -2, 2], 0))  # Expected output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]

                                        
This detailed methodology leverages sorting, recursion, and the two-pointer technique in pseudocode to precisely find all unique quadruplets summing up to a target value.