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, d are 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.

Visualization

Tap to expand
4Sum: The Card Sorting StrategyBefore: Chaotic Array10-12-2Sort!After: Sorted Array-2-1012Fixed: i=0(-2), j=1(-1)left pointerright pointerTwo-Pointer MagicSum = -2 + (-1) + 0 + 2 = -1Target = 0-1 < 0, so move left pointer →Continue until sum = targetSkip duplicates automatically!
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!

Time & Space Complexity

Time Complexity
⏱️
O(n³)

O(n log n) for sorting + O(n³) for three loops with two-pointer optimization

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using constant extra space (not counting output array)

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 200
  • -109 ≤ nums[i] ≤ 109
  • -109 ≤ target ≤ 109
  • All quadruplets must be unique (no duplicate quadruplets in result)
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.0K Views
High Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen