4Sum
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Two Pointers.
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
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
There are three unique quadruplets that sum to 0.
Approach 1
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.
⏱ O(N^4)💾 O(K) where K is the number of unique quadruplets
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.
Approach 2
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.⏱ O(N^3)💾 O(N)
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.
Approach 3
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).⏱ O(N^3)💾 O(1) (excluding sorting space)
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.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.