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
to reduce the N-sum problem into smaller problems until we reach the 2-sum problem.
findNsum -
First, we sort the array
to facilitate the two-pointer technique for the 2-sum problem.
nums -
The
function works as follows:
findNsum -
Base case: If
equals 2 (i.e., looking for pairs), use a two-pointer technique to find pairs that sum up to the reduced target.
N -
Recursive case: For
, loop through the array, and recursively reduce the problem to an (N-1)-sum problem while adjusting the target accordingly.
N > 2 - 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:
- Sort the array : Sorting helps to use the two-pointer technique effectively.
-
Recursive function
: Define a recursive function
.
findNsum -
Parameters
: Input array
, current target
nums, integercurrent_target(indicating the N-sum problem),N(stores the current quadruplet being constructed), andcurrent_result(stores all valid quadruplets).all_results - Base case for recursion :
-
If
is 2, use two pointers (
Nandleft) to find pairs that sum up toright.current_target - Adjust pointers and skip duplicates.
- Recursive case :
-
Iterate through the array, recursively call
to reduce the problem to (N-1)-sum, and adjust the target by subtracting the current element.
findNsum -
Initialize and call the recursion
: Call
from the main function with initial parameters.
findNsum - 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.