4Sum
Problem
Given an integer array nums and an integer target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that a, b, c, and d are distinct indices and nums[a] + nums[b] + nums[c] + nums[d] == target.
- 1 ≤ nums.length ≤ 200
- −10⁹ ≤ nums[i] ≤ 10⁹
- −10⁹ ≤ target ≤ 10⁹
Example
nums = [1, 0, -1, 0, -2, 2], target = 0[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]The brute-force approach would check all quadruplets, which is O(n^4) and infeasible for large inputs. The optimal approach sorts the array to enable skipping duplicates and uses nested loops combined with a two-pointer technique to find pairs that sum to the remaining target. For example, after fixing nums[i] = -2 and nums[j] = -1, the two pointers search for pairs summing to 3. The algorithm carefully moves pointers inward, skipping duplicates to avoid repeated quadruplets. This process repeats for all valid i and j, efficiently enumerating unique quadruplets.
Approach
Straightforward Solution
A brute-force approach enumerates all quadruplets with four nested loops, resulting in O(n^4) time complexity, which is impractical for larger inputs.
Core Observation
The problem requires finding quadruplets summing to a target, which can be decomposed into fixing two numbers and searching for two others that sum to the remaining target. Sorting the array enables efficient duplicate skipping and two-pointer search.
Path to Optimal
Sorting the array allows skipping duplicates and applying the two-pointer technique for the innermost pair search. Fixing the first two numbers with nested loops reduces the problem to a two-sum variant solvable in O(n) time. This reduces overall complexity to O(n^3). Duplicate quadruplets are avoided by skipping repeated values at each level.
Optimal Approach
Sort nums. Use two nested loops to fix the first two numbers (i and j). For each pair, use two pointers (left and right) to find pairs summing to target - nums[i] - nums[j]. Move pointers inward based on comparison with the remaining target, skipping duplicates to ensure unique quadruplets. Collect all valid quadruplets in the result list and return it.
Time
O(n^3)
Sorting takes O(n log n). The two nested loops run O(n^2) times, and for each pair, the two-pointer search runs in O(n), resulting in O(n^3) total time.
Space
O(n)
Sorting requires O(n) auxiliary space depending on the sorting algorithm. The output list space is not counted as auxiliary space.
Pattern Spotlight
Two Pointers (Nested Loops with Two-Pointer Pair Search)
When searching for k-sum problems, reduce the problem by fixing k-2 elements and use the two-pointer technique to find the remaining pair efficiently, while skipping duplicates to avoid repeated solutions.
Solution
| 1 | class Solution: |
| 2 | def fourSum(self, nums: list[int], target: int) -> list[list[int]]: |
| 3 | nums.sort() |
| 4 | result = [] |
| 5 | n = len(nums) |
| 6 | |
| 7 | for i in range(n - 3): |
| 8 | if i > 0 and nums[i] == nums[i - 1]: |
| 9 | continue |
| 10 | |
| 11 | for j in range(i + 1, n - 2): |
| 12 | if j > i + 1 and nums[j] == nums[j - 1]: |
| 13 | continue |
| 14 | |
| 15 | left = j + 1 |
| 16 | right = n - 1 |
| 17 | |
| 18 | while left < right: |
| 19 | current_sum = nums[i] + nums[j] + nums[left] + nums[right] |
| 20 | |
| 21 | if current_sum == target: |
| 22 | result.append([nums[i], nums[j], nums[left], nums[right]]) |
| 23 | |
| 24 | left += 1 |
| 25 | right -= 1 |
| 26 | |
| 27 | while left < right and nums[left] == nums[left - 1]: |
| 28 | left += 1 |
| 29 | |
| 30 | while left < right and nums[right] == nums[right + 1]: |
| 31 | right -= 1 |
| 32 | |
| 33 | elif current_sum < target: |
| 34 | left += 1 |
| 35 | else: |
| 36 | right -= 1 |
| 37 | |
| 38 | return result |
Step-by-Step Solution
Sort the Array and Initialize Result Container
| 3 | nums.sort() |
| 4 | result = [] |
| 5 | n = len(nums) |
Objective
To prepare the input for efficient duplicate skipping and two-pointer searching by sorting, and to create a container for storing valid quadruplets.
Key Insight
Sorting the array is essential because it enables the two-pointer technique and makes duplicate detection straightforward by comparing adjacent elements. Initializing the result list upfront provides a place to accumulate valid quadruplets as they are found.
Interview Quick-Check
Core Logic
Sorting transforms the problem into a structured search space where duplicates are adjacent, enabling efficient skipping.
Common Pitfalls & Bugs
Forgetting to sort the array leads to incorrect duplicate detection and inefficient searching.
Fix the First Number and Skip Its Duplicates
| 7 | for i in range(n - 3): |
| 8 | if i > 0 and nums[i] == nums[i - 1]: |
| 9 | continue |
Objective
To iterate over the array fixing the first number of the quadruplet and skip duplicates to avoid repeated quadruplets starting with the same number.
Key Insight
By fixing the first number, the problem reduces to finding triplets summing to target minus this fixed number. Skipping duplicates at this level prevents generating quadruplets that differ only in the first element, ensuring uniqueness and reducing unnecessary computation.
Interview Quick-Check
Core Logic
Skipping duplicates for the first number ensures each quadruplet's first element is unique, preventing redundant searches.
State & Boundaries
The loop runs until n-3 because we need at least three more numbers after the first.
Fix the Second Number and Skip Its Duplicates
| 11 | for j in range(i + 1, n - 2): |
| 12 | if j > i + 1 and nums[j] == nums[j - 1]: |
| 13 | continue |
Objective
To fix the second number of the quadruplet for each fixed first number and skip duplicates to maintain uniqueness.
Key Insight
Fixing the second number further reduces the problem to a two-sum search for the remaining two numbers. Skipping duplicates here prevents quadruplets with the same first two numbers from being counted multiple times, which is critical for correctness and efficiency.
Interview Quick-Check
Core Logic
Skipping duplicates for the second number ensures unique pairs for the remaining two-pointer search.
State & Boundaries
The loop runs until n-2 because two more numbers are needed after the second.
Use Two Pointers to Find Remaining Pair Summing to Target
| 15 | left = j + 1 |
| 16 | right = n - 1 |
| 18 | while left < right: |
| 19 | current_sum = nums[i] + nums[j] + nums[left] + nums[right] |
| 21 | if current_sum == target: |
| 22 | result.append([nums[i], nums[j], nums[left], nums[right]]) |
| 24 | left += 1 |
| 25 | right -= 1 |
| 27 | while left < right and nums[left] == nums[left - 1]: |
| 28 | left += 1 |
| 30 | while left < right and nums[right] == nums[right + 1]: |
| 31 | right -= 1 |
| 33 | elif current_sum < target: |
| 34 | left += 1 |
| 35 | else: |
| 36 | right -= 1 |
Objective
To use two pointers to efficiently find pairs that, combined with the fixed first and second numbers, sum to the target.
Key Insight
The two-pointer technique exploits the sorted array to find pairs summing to a specific value in O(n) time. By moving pointers inward based on the current sum relative to the target, the algorithm efficiently explores all valid pairs. Skipping duplicates after finding a valid quadruplet ensures uniqueness in the results.
Interview Quick-Check
Core Logic
Two pointers move inward from both ends, adjusting based on the sum compared to the target, enabling O(n) pair search.
Common Pitfalls & Bugs
Failing to skip duplicates after finding a valid quadruplet leads to repeated results.
State & Boundaries
The while loop continues as long as left < right, ensuring valid pairs.
Return the List of Unique Quadruplets
| 38 | return result |
Objective
To return the accumulated list of unique quadruplets that sum to the target.
Key Insight
After all iterations and two-pointer searches, the result list contains all unique quadruplets. Returning it completes the solution.
Interview Quick-Check
Core Logic
Returning the result list provides the final answer after exhaustive, duplicate-free search.
Line Analysis
This solution has 6 Critical lines interviewers watch for.
if i > 0 and nums[i] == nums[i - 1]:
Skip duplicate first numbers to avoid repeated quadruplets.
Since the array is sorted, duplicates appear consecutively; skipping repeated values here prevents generating quadruplets with the same first element multiple times.
if j > i + 1 and nums[j] == nums[j - 1]:
Skip duplicate second numbers to avoid repeated quadruplets.
Skipping duplicates at this level prevents quadruplets with the same first two numbers from being counted multiple times, ensuring uniqueness.
nums.sort()
Sort the input array to enable efficient two-pointer searching and duplicate skipping.
Sorting is essential because it structures the data, allowing the two-pointer technique to work correctly and enabling straightforward detection and skipping of duplicates by comparing adjacent elements.
if current_sum == target:
Check if the current sum equals the target.
Finding a sum equal to the target indicates a valid quadruplet to add to the result.
while left < right and nums[left] == nums[left - 1]:
Skip duplicate values at the left pointer to avoid repeated quadruplets.
Since the array is sorted, duplicates are adjacent; skipping them here prevents adding identical quadruplets multiple times.
while left < right and nums[right] == nums[right + 1]:
Skip duplicate values at the right pointer to avoid repeated quadruplets.
Skipping duplicates on the right pointer side prevents repeated quadruplets with the same right elements.
continue
Continue to the next iteration if the current first number is a duplicate.
This control flow ensures the loop skips processing for duplicate first numbers, maintaining result uniqueness and improving efficiency.
continue
Continue to the next iteration if the current second number is a duplicate.
This control flow avoids redundant processing for duplicate second numbers, improving correctness and efficiency.
current_sum = nums[i] + nums[j] + nums[left] + nums[right]
Calculate the sum of the four numbers at indices i, j, left, and right.
This sum determines whether the current quadruplet meets the target or if pointers need adjustment.
result.append([nums[i], nums[j], nums[left], nums[right]])
Append the valid quadruplet to the result list.
Storing the quadruplet here ensures all valid solutions are collected for the final output.
left += 1
Increment the left pointer while duplicates are detected.
This loop ensures the left pointer moves past all duplicates, maintaining uniqueness in results.
right -= 1
Decrement the right pointer while duplicates are detected.
This loop moves the right pointer past duplicates, ensuring unique quadruplets.
for i in range(n - 3):
Start the outer loop to fix the first number of the quadruplet.
Fixing the first number reduces the problem to finding triplets summing to target minus this number, enabling a layered search approach.
for j in range(i + 1, n - 2):
Start the inner loop to fix the second number of the quadruplet.
Fixing the second number further reduces the problem to finding pairs summing to the remaining target, enabling the two-pointer search.
while left < right:
Begin the two-pointer search loop while left is less than right.
The loop condition ensures valid pairs are considered without overlap or reversal of pointers.
left += 1
Move the left pointer inward to look for new pairs.
After finding a valid quadruplet, moving left inward explores other potential pairs while avoiding duplicates.
right -= 1
Move the right pointer inward to look for new pairs.
Similarly, moving right inward after a valid quadruplet explores other pairs and avoids duplicates.
elif current_sum < target:
Check if the current sum is less than the target.
If the sum is too small, moving the left pointer inward increases the sum due to sorting.
left += 1
Increment the left pointer to increase the sum.
Moving left inward increases the sum because the array is sorted in ascending order.
else:
Handle the case where the current sum is greater than the target.
If the sum is too large, moving the right pointer inward decreases the sum.
right -= 1
Decrement the right pointer to decrease the sum.
Moving right inward decreases the sum due to the sorted order, helping approach the target.
left = j + 1
Initialize the left pointer just after the second fixed number.
The left pointer starts at the next index to search for pairs that complete the quadruplet.
right = n - 1
Initialize the right pointer at the end of the array.
The right pointer starts at the array's end to enable inward movement during the two-pointer search.
return result
Return the list of unique quadruplets found.
Returning the result completes the function, providing all quadruplets that sum to the target without duplicates.
result = []
Initialize an empty list to store the resulting quadruplets.
This list accumulates all unique quadruplets found during the search, serving as the output container.
n = len(nums)
Store the length of the input array for loop boundaries.
Caching the length avoids repeated calls to len(nums) and clarifies loop limits.
Test Your Understanding
Why is it necessary to skip duplicates at each level of the nested loops and during the two-pointer search?
Skipping duplicates prevents adding identical quadruplets multiple times, ensuring the result contains only unique quadruplets. Since the array is sorted, duplicates appear consecutively, so skipping repeated values at each step avoids redundant work and duplicate results.
Related Problems
Two Pointers pattern
Don't just read it. Drill it.
Reconstruct 4Sum from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the 4Sum drill