3Sum (LeetCode 15): Solution and Explanation
Given an integer array, return every distinct triplet of values at three different positions whose sum is zero. The output must not contain the same triplet twice, though the order of triplets does not matter.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force tries every combination of three indices, which is O(n³), and then needs a set of sorted tuples to remove duplicate triplets. Both parts are wasteful. A better framing: if you fix the first number a, you need two more numbers that sum to -a. That is exactly Two Sum, so 3Sum is n copies of Two Sum, one per choice of a.
Sorting the array first makes each of those Two Sum problems cheap and also tames duplicates. With the rest of the array sorted, the two pointer technique finds every pair summing to -a in linear time: start l just after a and r at the end, move r left when the sum is too big and l right when it is too small. That brings the total to O(n²), which is the expected bound for this problem.
Sorting is also what makes duplicate handling clean. Equal values sit next to each other, so if a equals the previous first number, every triplet it could produce has already been found, and you skip it. Inside the two pointer loop, after recording a triplet you move l forward past any copies of the value you just used, so the same pair is not reported again for this a. Those two skips are the whole difference between a correct answer and one with repeated triplets.
Approach: Sort, then two pointers for each anchor
- Sort
numsin ascending order and create an empty result listres. - Loop over each index
iand valuea. Ifi > 0anda == nums[i - 1], skip it to avoid duplicate triplets. - Set
l = i + 1andr = len(nums) - 1. - While
l < r, computethreeSum = a + nums[l] + nums[r]. - If the sum is positive, decrement
r. If it is negative, incrementl. - If the sum is zero, append
[a, nums[l], nums[r]], incrementl, then keep incrementinglwhilenums[l] == nums[l - 1]andl < r. - Return
resafter every anchor has been processed.
Step-by-step example
nums = [-1, 0, 1, 2, -1, -4]
- After sorting, nums = [-4, -1, -1, 0, 1, 2].
- i = 0, a = -4: the largest possible sum is -4 + 1 + 2 = -1, so every check is negative and
lwalks right until it meetsr. No triplet. - i = 1, a = -1: l = 2, r = 5 gives -1 + -1 + 2 = 0. Record [-1, -1, 2]. Move l to 3; nums[3] = 0 differs from nums[2], so stop skipping.
- Still a = -1: l = 3, r = 5 gives -1 + 0 + 2 = 1, too big, so r = 4. Then -1 + 0 + 1 = 0, so record [-1, 0, 1] and move l to 4, where l meets r.
- i = 2, a = -1 equals nums[1], so skip. i = 3, a = 0: 0 + 1 + 2 = 3, r moves left until it meets l. Nothing else is found.
- Return [[-1, -1, 2], [-1, 0, 1]].
Code: Python, Java, C++
1class Solution:
2 def threeSum(self, nums: List[int]) -> List[List[int]]:
3 res = []
4 nums.sort()
5
6 for i, a in enumerate(nums):
7 if i > 0 and a == nums[i - 1]:
8 continue
9
10 l, r = i + 1, len(nums) - 1
11 while l < r:
12 threeSum = a + nums[l] + nums[r]
13 if threeSum > 0:
14 r -= 1
15 elif threeSum < 0:
16 l += 1
17 else:
18 res.append([a, nums[l], nums[r]])
19 l += 1
20 while nums[l] == nums[l - 1] and l < r:
21 l += 1
22 return res1class Solution {
2 public List<List<Integer>> threeSum(int[] nums) {
3 Arrays.sort(nums);
4 List<List<Integer>> res = new ArrayList<>();
5
6 for (int i = 0; i < nums.length; i++) {
7 if (i > 0 && nums[i] == nums[i - 1]) continue;
8
9 int l = i + 1, r = nums.length - 1;
10 while (l < r) {
11 int sum = nums[i] + nums[l] + nums[r];
12 if (sum > 0) {
13 r--;
14 } else if (sum < 0) {
15 l++;
16 } else {
17 res.add(Arrays.asList(nums[i], nums[l], nums[r]));
18 l++;
19 while (l < r && nums[l] == nums[l - 1]) {
20 l++;
21 }
22 }
23 }
24 }
25 return res;
26 }
27}1class Solution {
2public:
3 vector<vector<int>> threeSum(vector<int>& nums) {
4 vector<vector<int>> res;
5 sort(nums.begin(), nums.end());
6
7 for (int i = 0; i < nums.size(); i++) {
8 if (i > 0 && nums[i] == nums[i - 1]) continue;
9
10 int l = i + 1, r = nums.size() - 1;
11 while (l < r) {
12 int sum = nums[i] + nums[l] + nums[r];
13 if (sum > 0) {
14 r--;
15 } else if (sum < 0) {
16 l++;
17 } else {
18 res.push_back({nums[i], nums[l], nums[r]});
19 l++;
20 while (l < r && nums[l] == nums[l - 1]) {
21 l++;
22 }
23 }
24 }
25 }
26 return res;
27 }
28};Time and space complexity
O(n²)
Sorting costs O(n log n). Then for each of the n anchors, the two pointers together traverse at most n positions, giving O(n²), which dominates.
O(1) extra
Apart from the output list, only a few indices are used. Python's sort itself may use up to O(n) auxiliary memory internally.
Other approaches
Hash set per anchor (time O(n²), space O(n))
For each anchor, scan the rest of the array with a set of seen values to find pairs summing to -a, and collect sorted triplets in a set to deduplicate. It avoids two pointer logic but uses more memory and makes duplicate handling clumsier.
Brute force with a result set (time O(n³), space O(n))
Try every triple of indices and store each sorted triplet in a set. It is easy to verify but cubic, so it only works for very small inputs.
Common mistakes
- Skipping duplicate anchors with
nums[i] == nums[i + 1]instead of comparing with the previous element. That skips the first copy, which is the one that can pair with its own duplicate, and misses triplets like [-1, -1, 2]. - Forgetting to move past duplicate
lvalues after recording a triplet, which produces repeated triplets such as [-2, 0, 2] twice for [-2, 0, 0, 2, 2]. - Not advancing any pointer after a match. Without
l += 1the loop records the same triplet forever. - Trying to deduplicate by converting the result to a set of lists. Lists are unhashable in Python, and sorting plus skipping is cheaper anyway.
Frequently asked questions
Why do we sort the array in 3Sum?
Sorting lets the two pointer technique find pairs in linear time and puts duplicates next to each other, so they can be skipped with a simple comparison to the previous element.
Can 3Sum be solved faster than O(n²)?
Not in any practical general-purpose way. O(n²) is the standard bound, and only highly specialized theoretical algorithms shave off small logarithmic factors.
How do you avoid duplicate triplets in 3Sum?
Skip an anchor when it equals the previous anchor, and after recording a triplet, advance the left pointer past all copies of its current value. Both rely on the array being sorted.
Can I stop early when the anchor is positive?
Yes. Once the anchor is greater than zero, every remaining value is also positive, so no triplet can sum to zero. It is a safe optimization the reference code does not include.