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
Visualization
Time & Space Complexity
O(n log n) for sorting + O(n³) for three loops with two-pointer optimization
Only using constant extra space (not counting output array)
Constraints
- 1 ≤ nums.length ≤ 200
- -109 ≤ nums[i] ≤ 109
- -109 ≤ target ≤ 109
- All quadruplets must be unique (no duplicate quadruplets in result)