3Sum
Master this topic with zero to advance depth.
3Sum
Given an integer array nums, return all the unique triplets [nums[i], nums[j], nums[k]] such that i \neq j, i \neq k, and j \neq k, and nums[i] + nums[j] + nums[k] == 0.
Visual Representation
Sorted Array: [-4, -1, -1, 0, 1, 2]
Step 1: Fix i = -1 (Index 1)
L = -1 (Index 2), R = 2 (Index 5)
Sum = -1 + (-1) + 2 = 0 -> FOUND! [-1, -1, 2]
Step 2: L moves to 0 (Index 3), R moves to 1 (Index 4)
Sum = -1 + 0 + 1 = 0 -> FOUND! [-1, 0, 1]Examples
The triplets are (-1, 0, 1) and (-1, -1, 2).
Level I: Brute Force (Check All Triplets)
Intuition
Check every possible combination of three numbers to see if they sum to zero. To avoid duplicate triplets, we can sort each triplet and store it in a Set.
Detailed Dry Run
| i | j | k | nums[i] | nums[j] | nums[k] | Sum | Result | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | 0 | 1 | 2 | -1 | 0 | 1 | 0 | FOUND! [-1, 0, 1] |
⚠️ Common Pitfalls & Tips
O(N^3) complexity is too slow for N > 1000.
Level II: Better (Sorting + Binary Search)
Intuition
If we sort the array and fix two elements nums[i] and nums[j], we need to find -(nums[i] + nums[j]) in the remaining part of the array. Since it is sorted, we can use binary search.
- Sort the array.
- Fix two pointers
iandj. - Search for the required third value using binary search in the range
(j+1, n-1).
Detailed Dry Run
Input: [-1, 0, 1, 2, -1, -4]. Sorted: [-4, -1, -1, 0, 1, 2]
i=-4, j=-1: Search for5? Not found.i=-1, j=-1: Search for2? FOUND at index 5. Result:[-1, -1, 2].i=-1, j=0: Search for1? FOUND at index 4. Result:[-1, 0, 1].
⚠️ Common Pitfalls & Tips
O(N^2 log N) is better than O(N^3) but still not as good as the O(N^2) two-pointer solution.
Level III: Optimal (Sort + Two Pointers)
Intuition
To optimize, we sort the array first. This allows us to use the Two Pointers technique for the 'Two Sum' part of the problem.
- Fix the first element
nums[i]. - Use Two Pointers (
L = i+1, R = n-1) to find pairs that sum to-nums[i]. - Skip duplicate values for
i,L, andRto ensure unique triplets.
Detailed Dry Run
Input: [-1, 0, 1, 2, -1, -4]. Sorted: [-4, -1, -1, 0, 1, 2]
| i | val[i] | L | R | Sum | Action |
|---|---|---|---|---|---|
| 0 | -4 | 1 (-1) | 5 (2) | -3 | Sum < 0, L++ |
| 1 | -1 | 2 (-1) | 5 (2) | 0 | FOUND! L++, R-- |
| 1 | -1 | 3 (0) | 4 (1) | 0 | FOUND! L++, R-- |
⚠️ Common Pitfalls & Tips
Remember to skip duplicate values for all three pointers to avoid duplicate triplets in the result.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.