Problem overview
The method threeSum takes a vector<int> named nums and returns every triplet of values that adds up to 0, taken from three different indices. The answer must not contain duplicates: triplets made of the same three values count once, whichever indices they come from. Each triplet is written in ascending order, and the triplets themselves are in ascending order, comparing first values, then second, then third.
For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. The value -1 appears twice, so -1, 0, 1 can be built in two ways, but it is listed once. For [0, 0, 0, 0] the answer is [[0, 0, 0]], and for [0, 1, 1] it is empty. The statement asks for O(n²) time and O(1) extra space, apart from sorting and the returned triplets.
Approach: fix one number, then run two pointers
Trying every triple of indices costs O(n³), which is far too slow for 3000 elements, and removing duplicates afterwards needs extra work. Sorting first fixes both problems.
Once nums is sorted, fix the first number of the triplet at index i. The other two numbers must lie to its right and add up to -nums[i]. Searching for a pair with a given sum in a sorted range is the classic two-pointer job: start one pointer at each end of the range and compare the sum.
- If the total is below 0, the sum is too small. The only way to raise it is to move
leftto a bigger value. - If the total is above 0, move
rightto a smaller value. - If the total is 0, record the triplet and move on.
Each value of i costs O(n) for the pointer walk, so the whole thing is O(n²). The sort costs O(n log n), which is smaller.
Sorting also makes duplicates easy to skip, because equal values sit next to each other. And since the scan goes left to right through a sorted vector, with i < left < right, every triplet is already in ascending order and the triplets come out in ascending order too. No final sort is needed.
Step by step
- Sort
numswithsort(nums.begin(), nums.end()). - Store the length in an
intnamedn. - Create an empty
vector<vector<int>>namedresult. Each element is one triplet. - Loop over the first number with
ifrom 0 whilei < n - 2. The other two numbers sit to the right, soistops two places before the end. - Skip repeated first numbers. If
i > 0andnums[i] == nums[i - 1],continue. The same first value would find the same triplets again. - Set the pointers:
left = i + 1andright = n - 1. - Loop while
left < right. When they meet, every pair for thisihas been considered. - Compute
totalasnums[i] + nums[left] + nums[right]. - Total below 0:
left++. - Total above 0:
right--. - Total equal to 0:
push_backthe braced list{nums[i], nums[left], nums[right]}. - Move both pointers inward after a hit. Keeping one in place would need the other one's old value again, which gives the same triplet.
- Skip repeated second numbers: while
left < rightandnums[left] == nums[left - 1], doleft++. There is no matching loop forright: ifrightstill holds an old value, the total is now too big, and the "above 0" branch moves it. - Return
resultafter the loops.
The solution in C++
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<vector<int>> result;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = n - 1;
while (left < right) {
int total = nums[i] + nums[left] + nums[right];
if (total < 0) {
left++;
} else if (total > 0) {
right--;
} else {
result.push_back({nums[i], nums[left], nums[right]});
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
}
}
}
return result;
}
};
The C++ details worth knowing:
sortchanges the caller's vector.numsis a reference, so after the call the caller's vector is sorted. That is fine for this problem, but it is a side effect. Pass the vector by value if you need to keep the original order.nis aninton purpose.nums.size()is unsigned, sonums.size() - 2would wrap to a huge number for a vector with fewer than two elements. Copying the size into anintkeepsn - 2an ordinary signed value. The constraints promise at least three elements, so the loop is safe here.push_back({a, b, c})builds a newvector<int>of three numbers from the braced list and adds it toresult.continueskips the rest of the loop body and moves to the nexti. The shortif (...) continue;on one line is legal when the body is a single statement.- The sum can't overflow. Values stay within plus or minus 100000, so the sum of three fits easily in an
int.
Tracing the example
After sorting, [-1, 0, 1, 2, -1, -4] becomes [-4, -1, -1, 0, 1, 2]. These are the checks the loops make:
| i | left | right | total | Action |
|---|---|---|---|---|
| 0 | 1 | 5 | -3 | too small, move left |
| 0 | 2 | 5 | -3 | too small, move left |
| 0 | 3 | 5 | -2 | too small, move left |
| 0 | 4 | 5 | -1 | too small, move left, then the pointers meet |
| 1 | 2 | 5 | 0 | record [-1, -1, 2] |
| 1 | 3 | 4 | 0 | record [-1, 0, 1] |
| 2 | - | - | - | skipped: nums[2] equals nums[1] |
| 3 | 4 | 5 | 3 | too big, move right, then the pointers meet |
The loop over i ends there because i < n - 2 means i < 4. The result is [[-1, -1, 2], [-1, 0, 1]].
Complexity
Time is O(n²). Sorting is O(n log n). For each i, left and right together move at most n steps, because each step moves one of them inward and they never move back.
Extra space is O(1) apart from the sort's internal needs and the returned triplets, as the statement allows.
Edge cases and common mistakes
- All zeros.
[0, 0, 0, 0]gives one triplet,[0, 0, 0]. After recording it,leftandrightmove inward, the duplicate-skipping loop runs whileleft < right, and the pointers meet. Later values ofiare skipped as repeats. Exactly three zeros give the same single triplet. - No answer.
[0, 1, 1]returns an empty vector. - Repeated values inside a triplet. The example's
[-1, -1, 2]uses the same value twice, from two different indices. That is allowed. The duplicate skipping only rejects a repeat of the same first value, or of the same second value after a hit. - Skipping duplicates by comparing with the next element. Checking
nums[i] == nums[i + 1]instead ofnums[i - 1]would skip the first copy of a value, and so lose triplets like[-1, -1, 2]. Compare with the previous element, so the first copy is processed and later copies are skipped. - Forgetting to move both pointers after a hit. If neither moves, the loop runs forever on the same total.
- A bigger example. For
[-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6]the answer is[[-4, -2, 6], [-4, 0, 4], [-4, 1, 3], [-4, 2, 2], [-2, -2, 4], [-2, 0, 2]]. Each triplet appears once, even though 6, 4, 3, 2 and -2 each repeat in the input.
