3Sum
Find every distinct triple of values in an array that adds up to zero. Sorting plus a two-pointer sweep turns the cubic search into a quadratic one. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given an integer array nums. Return every distinct triplet [a, b, c] of values such that a + b + c == 0 and the three values come from three different positions in the array.
Two triplets count as the same if they contain the same values, so the answer must not contain duplicates like [-1, 0, 1] and [0, 1, -1]. You may return the triplets in any order, and the values within each triplet in any order.
Example 1
- Input
- nums = [-3, 1, 2, -1, 0, 4]
- Output
- [[-3, 1, 2], [-3, -1, 4], [-1, 0, 1]]
Example 2
- Input
- nums = [0, 0, 0, 0]
- Output
- [[0, 0, 0]]
Four zeros can form several index triples, but they all give the same values, so it is listed once.
Example 3
- Input
- nums = [1, 2, -4, 5]
- Output
- []
No three of these values add up to zero.
Constraints
- 3 ≤ nums.length ≤ 3000
- -10⁵ ≤ nums[i] ≤ 10⁵
Practice
Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked 3Sum in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve 3Sum
Pattern: Sort + two pointers
Fix one value a, and the rest of the problem is "find two values that sum to -a", which is Two Sum. On a sorted array, Two Sum takes a single two-pointer sweep: start at both ends, and move the left pointer up when the sum is too small or the right pointer down when it's too big.
Sorting also solves the duplicate problem for free. Equal values end up next to each other, so you can skip a repeated a in the outer loop and skip repeated values after recording a triplet in the inner sweep. Every triplet then comes out in non-decreasing order exactly once, with no set needed.
Another hint: once the sorted a is positive, everything to its right is positive too, so no further triplet can sum to zero.
Approach 1: Brute force: try every triple
Three nested loops over i < j < k, keeping triplets that sum to zero. Sort each triplet and store it in a set to remove duplicates. Correct, but 3000 elements means about 4.5 × 10⁹ triples.
Time O(n³) · Space O(answer)
Approach 2: Fix one value, hash set for the other two
For each i, walk j from i + 1 and check whether -(nums[i] + nums[j]) was seen earlier in this inner loop, using a set. Sorting the result triplets and de-duplicating them through a set of tuples keeps the output distinct. Quadratic, but the de-duplication is fiddly and the hashing adds constant overhead.
Time O(n²) · Space O(n)
Approach 3: Sort, then two pointers for each fixed value
- Sort
nums. - For each index
i(stopping oncenums[i] > 0), skip it ifnums[i] == nums[i - 1]. - Set
lo = i + 1,hi = n - 1. Whilelo < hi, compute the sum. If it's negative moveloright, if positive movehileft. - On a zero sum, record the triplet, then move
loright past every copy of its value andhileft past every copy of its value.
The sort costs O(n log n), and each of the n outer steps does one linear sweep.
Time O(n²) · Space O(1) extra besides the sort and output
| Approach | Time | Space |
|---|---|---|
| Brute force: try every triple | O(n³) | O(answer) |
| Fix one value, hash set for the other two | O(n²) | O(n) |
| Sort, then two pointers for each fixed value | O(n²) | O(1) extra besides the sort and output |
Solution code
Try the practice editor first. Both solutions pass every test above.
3Sum solution in Python
def three_sum(nums: list[int]) -> list[list[int]]:
nums = sorted(nums)
n = len(nums)
result = []
for i in range(n - 2):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
lo, hi = i + 1, n - 1
while lo < hi:
total = nums[i] + nums[lo] + nums[hi]
if total < 0:
lo += 1
elif total > 0:
hi -= 1
else:
result.append([nums[i], nums[lo], nums[hi]])
lo += 1
hi -= 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1
while lo < hi and nums[hi] == nums[hi + 1]:
hi -= 1
return result3Sum solution in JavaScript
function threeSum(nums) {
const sorted = [...nums].sort((a, b) => a - b);
const n = sorted.length;
const result = [];
for (let i = 0; i < n - 2; i++) {
if (sorted[i] > 0) break;
if (i > 0 && sorted[i] === sorted[i - 1]) continue;
let lo = i + 1;
let hi = n - 1;
while (lo < hi) {
const total = sorted[i] + sorted[lo] + sorted[hi];
if (total < 0) {
lo++;
} else if (total > 0) {
hi--;
} else {
result.push([sorted[i], sorted[lo], sorted[hi]]);
lo++;
hi--;
while (lo < hi && sorted[lo] === sorted[lo - 1]) lo++;
while (lo < hi && sorted[hi] === sorted[hi + 1]) hi--;
}
}
}
return result;
}Common mistakes
- Skipping duplicates of the fixed value by comparing nums[i] with nums[i + 1] instead of nums[i - 1]. That skips the first copy and misses triplets like [-1, -1, 2].
- Forgetting to skip duplicates after a match, which records the same triplet several times.
- Stopping the inner sweep after the first match. One fixed value can pair with several different (b, c) pairs, as -3 does with [1, 2] and [-1, 4].
- Returning indices instead of values.
What interviewers look for
Open by connecting it to Two Sum: "if I fix one number, I need two others that sum to its negative." Then explain why you sort: it unlocks the two-pointer sweep and makes duplicate handling a matter of skipping neighbors. Interviewers are mostly checking whether you can de-duplicate cleanly without leaning on a set of tuples.
Before finishing, trace an input with heavy duplicates such as [-1, -1, 2, 2] or all zeros. That's where off-by-one skip logic breaks.
Follow-up questions
How would you solve 4Sum, or k-Sum in general?
Sort once, then fix values recursively: k-Sum fixes one value and calls (k-1)-Sum on the rest, bottoming out at the two-pointer 2-Sum. Skip duplicate values at every level. It runs in O(n^(k-1)).
What if you need the triplet whose sum is closest to a target instead of exactly zero?
Use the same sort and two-pointer sweep, but track the sum with the smallest absolute difference from the target as you go, moving pointers by whether the current sum is below or above the target.
What if you only need to count triplets, not list them, and duplicates by position count separately?
Count value frequencies and iterate over value pairs a ≤ b, looking up c = -a - b with c ≥ b. Combine the counts with combinations (choose 2 or choose 3 when values repeat). That avoids walking over equal values one by one.
Companies that ask 3Sum
3Sum is tagged by 128 companies in our interview dataset. The score shows how often it comes up at each company.
- Adevinta100%
- Bigcommerce100%
- Wissen Technology100%
- Works Applications100%
- Visa92.9%
- Disco Corporation92%
- Cerner91%
- Highradius90%
- Trexquant89%
- Oyo87.9%
- Wixcom87.3%
- Adobe84.3%
- Gopuff84%
- Motorola84%
- Zego83%
- Wizeline81%
- Cloudflare81%
- Workiva80%
- Bloomberg79.6%
- Roku79.3%
- Walmart Labs78.4%
- Amazon78.3%
- Keysight78%
- Qualcomm75.6%
and 104 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required