4Sum - Problem
Welcome to the 4Sum Problem - a fascinating challenge that extends the classic Two Sum problem into multiple dimensions!
You're given an array nums containing n integers and a target value. Your mission is to find all unique quadruplets (groups of four numbers) [nums[a], nums[b], nums[c], nums[d]] where:
- All four indices
a, b, c, dare different - The sum equals the target:
nums[a] + nums[b] + nums[c] + nums[d] == target
Example: Given nums = [1,0,-1,0,-2,2] and target = 0, you should return [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
The beauty of this problem lies in efficiently avoiding duplicates while exploring all possible combinations. Can you find all the hidden quadruplets? 🎯
Input & Output
example_1.py — Basic Case
$
Input:
nums = [1,0,-1,0,-2,2], target = 0
›
Output:
[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
💡 Note:
The three unique quadruplets that sum to 0 are: -2+(-1)+1+2=0, -2+0+0+2=0, and -1+0+0+1=0.
example_2.py — Empty Result
$
Input:
nums = [2,2,2,2,2], target = 8
›
Output:
[[2,2,2,2]]
💡 Note:
The only quadruplet is [2,2,2,2] which sums to 8, matching our target.
example_3.py — No Valid Quadruplets
$
Input:
nums = [1,2,3], target = 10
›
Output:
[]
💡 Note:
Array has less than 4 elements, so no quadruplets are possible.
Constraints
- 1 ≤ nums.length ≤ 200
- -109 ≤ nums[i] ≤ 109
- -109 ≤ target ≤ 109
- All quadruplets must be unique (no duplicate quadruplets in result)
Visualization
Tap to expand
Understanding the Visualization
1
Sort the Cards
Arrange all cards in ascending order to enable systematic searching
2
Fix Two Anchors
Choose the first two cards as anchor points
3
Two-Pointer Search
Use two pointers from opposite ends to find the perfect complementary pair
4
Skip Duplicates
Move past identical cards to ensure unique combinations
Key Takeaway
🎯 Key Insight: Sorting transforms a chaotic O(n⁴) brute force search into an elegant O(n³) two-pointer dance, where duplicates naturally avoid themselves!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code