4Sum
Master this topic with zero to advance depth.
4Sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that their sum is equal to target (0 <=q a, b, c, d < n and are distinct).
Visual Representation
Sorted: [-2, -1, 0, 0, 1, 2], Target: 0
Step 1: Fix i = -2, j = -1
L = 0, R = 2
Sum = -2 + (-1) + 1 + 2 = 0 -> FOUND! [-2, -1, 1, 2]
Step 2: Fix i = -2, j = 0
L = 0, R = 2
Sum = -2 + 0 + 0 + 2 = 0 -> FOUND! [-2, 0, 0, 2]Examples
There are three unique quadruplets that sum to 0.
Level I: Brute Force (Check All Quadruplets)
Intuition
Try every possible combination of four numbers to see if they sum up to the target. To avoid duplicates, we sort each quadruplet and store it in a Set.
Detailed Dry Run
Input: [1, 0, -1, 0, -2, 2], Target: 0
Combination (1, 0, -1, 0) -> Sum 0. Found!
Combination (1, 0, -2, 2) -> Sum 1. Skip.
...
⚠️ Common Pitfalls & Tips
O(N^4) will TLE for N > 200.
Level II: Sorting + HashSet
Intuition
By sorting and using a HashSet for the fourth element, we can reduce the complexity to O(N^3). It's essentially 3Sum but with one more outer loop.
Fix three pointers i, j, k, and check if target - (nums[i] + nums[j] + nums[k]) exists in a HashSet of the remaining elements.
Detailed Dry Run
Input: [1, 0, -1, 0, -2, 2], Target: 0
- Fix
1, 0, -1. Need0. Found0in the array. Quads:[1, 0, -1, 0]. - Fix
1, 0, -2. Need1. Found1. Quads:[1, 0, -2, 1]... No,1was already used. Use indices to avoid reuse.
⚠️ Common Pitfalls & Tips
O(N^3) is still slow for very large constraints but works for N=200-500.
Level III: Optimal (Sort + Two Pointers)
Intuition
This is a direct extension of 3Sum. We sort the array and use two nested loops to fix the first two numbers (i and j). Then we use the Two Pointer technique to find the remaining two numbers (L and R).
Detailed Dry Run
Sorted: [-2, -1, 0, 0, 1, 2], Target: 0
| i | j | L | R | Sum | Action |
|---|---|---|---|---|---|
| -2 | -1 | 0 | 1 | -3 | Sum < 0, L++ |
| -2 | -1 | 1 | 2 | 0 | FOUND! L++, R-- |
| -2 | 0 | 0 | 2 | 0 | FOUND! L++, R-- |
⚠️ Common Pitfalls & Tips
Be mindful of integer overflow in Java/C++ when adding four large integers. Use long or long long for the sum.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.