Problem overview
The method threeSum(nums) receives an array of integers and returns every triplet of values [nums[i], nums[j], nums[k]] that adds up to 0, using three different indices. The answer must not contain the same triplet twice: three values count once, whichever indices they come from. Each triplet is written in ascending order, and the triplets are listed in ascending order too, compared by first value, then second, then third.
For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. Several index choices give [-1, 0, 1], but it is listed once. For [0, 0, 0, 0] the answer is [[0, 0, 0]], and for [0, 1, 1] it is [].
Approach: fix one number, then walk two pointers
Trying every triple of indices costs O(n³), and removing duplicates afterwards needs extra work. The statement asks for O(n²), which comes from sorting first and then handling the problem as a series of two-number searches.
- Sort
numsin ascending order. Equal values end up side by side, so repeats are easy to skip, and the sums behave predictably. - Fix the first number
nums[i]. The other two must come from the part of the array to its right. - Search that part with two pointers:
leftstarts just afteriandrightat the last index. Add the three values:- if the total is below 0, move
leftright: in a sorted array that is the only way to make the sum bigger; - if the total is above 0, move
rightleft to make it smaller; - if the total is 0, record the triplet and move both pointers inward.
- if the total is below 0, move
Each pointer only moves in one direction, so the scan for one i takes O(n), and n values of i give O(n²). Because the array is sorted and the loop goes from left to right, every triplet comes out in ascending order, with its three values ascending too (i < left < right). The answer needs no sorting at the end.
Duplicates are removed in two places. A first number equal to the previous one is skipped, since it would find the same triplets again. After a hit, left advances past values equal to the one just used. The right pointer needs no such loop: once left has moved to a larger value, a repeated value at right makes the total positive, and the existing branch moves it.
Here is the scan on the sorted array [-4, -1, -1, 0, 1, 2]:
| i | left | right | total | action |
|---|---|---|---|---|
| 0 | 1 | 5 | -3 | move left |
| 0 | 2 | 5 | -3 | move left |
| 0 | 3 | 5 | -2 | move left |
| 0 | 4 | 5 | -1 | move left; the pointers meet |
| 1 | 2 | 5 | 0 | record [-1, -1, 2] |
| 1 | 3 | 4 | 0 | record [-1, 0, 1] |
| 2 | skipped: same value as index 1 | |||
| 3 | 4 | 5 | 3 | move right; the pointers meet |
Step by step
- Sort
numswith the comparator(a, b) => a - b. Without a comparator,sortcompares numbers as text. - Store the length in
n, used by the loop bounds. - Create an empty
resultto collect triplets in the order they are found. - Loop over the first number with
i < n - 2, because two more values must fit to its right. - Skip repeated first numbers with
continuewheni > 0andnums[i] === nums[i - 1]. - Set the pointers:
left = i + 1andright = n - 1. - Loop while
left < right. When they meet, all pairs for thisiare checked. - Add the three numbers into
total. - Total below 0: increment
left. - Total above 0: decrement
right. - Total equal to 0: push
[nums[i], nums[left], nums[right]]. - Move both pointers inward. Keeping one in place would need the other's value again, which gives the same triplet.
- Skip equal second numbers with an inner
whilethat incrementsleftwhilenums[left] === nums[left - 1]. - Return
result.
The solution in JavaScript
class Solution {
threeSum(nums) {
nums.sort((a, b) => a - b);
const n = nums.length;
const result = [];
for (let i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1, right = n - 1;
while (left < right) {
const total = nums[i] + nums[left] + nums[right];
if (total < 0) {
left++;
} else if (total > 0) {
right--;
} else {
result.push([nums[i], nums[left], nums[right]]);
left++;
right--;
while (left < right && nums[left] === nums[left - 1]) {
left++;
}
}
}
}
return result;
}
}
Some JavaScript details worth knowing:
- The comparator matters.
[10, 9, 1, -5, -12].sort()gives[-12, -5, 1, 10, 9], because the numbers are compared as strings. With(a, b) => a - bit gives[-12, -5, 1, 9, 10]. The subtraction is safe here, since the values stay within plus or minus 100,000. sortchanges the array it is called on. AfterthreeSum([3, -1, -2, 10, -10, 0])the caller's array reads[-10, -2, -1, 0, 3, 10]. If the caller needs the original order, sort a copy with[...nums].sort(...).===for comparing values. Numbers are compared by value, sonums[i] === nums[i - 1]detects a repeat.- One-line
ifwithcontinue.continueskips the rest of the loop body and goes on to the nexti, so no braces are needed for a single statement. - Triplets are new arrays. Every
push([...])creates a fresh three-element array, so the entries ofresultdon't share anything.
Complexity
Time: O(n²). Sorting costs O(n log n). The outer loop runs about n times, and for each i the two pointers together move at most n steps. The quadratic part dominates.
Space: O(1) extra, apart from the sort's own working space and the triplets returned. The function keeps only a handful of variables.
Edge cases and common mistakes
- Comparing with the next element instead of the previous one. The check for a repeated first number looks back, at
nums[i - 1], so the first copy of a value is always tried. - Forgetting the comparator. A default
sort()orders numbers as text, which breaks the two-pointer logic as soon as the values have different numbers of digits or signs. - All zeros.
[0, 0, 0, 0]gives one triplet,[[0, 0, 0]]. After the first hit,leftandrightmove inward and meet, and later values ofiare skipped as repeats. - Exactly three elements.
[1, 2, -3]gives[[-3, 1, 2]], and[0, 0, 0]gives[[0, 0, 0]]. With fewer than three, the loop boundn - 2would never allow an iteration. - Repeated values in one triplet.
[-2, 0, 1, 1, 2]gives[[-2, 0, 2], [-2, 1, 1]]. Repeats are skipped only for the first number of a newiand after a hit, so[-2, 1, 1]is still found. - No triplet.
[0, 1, 1]returns[], an empty array.
Testing
[-1, 0, 1, 2, -1, -4]gives[[-1, -1, 2], [-1, 0, 1]].[0, 1, 1]gives[].[0, 0, 0, 0]gives[[0, 0, 0]].[-2, 0, 1, 1, 2]gives[[-2, 0, 2], [-2, 1, 1]].[3, -1, -2, 10, -10, 0]gives[[-10, 0, 10], [-2, -1, 3]].[-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6]gives[[-4, -2, 6], [-4, 0, 4], [-4, 1, 3], [-4, 2, 2], [-2, -2, 4], [-2, 0, 2]].
