Problem overview
The method threeSum receives an array of numbers, nums, and returns every triplet [nums[i], nums[j], nums[k]] that adds up to 0, where i, j and k are three different indices. A triplet made of the same three values counts once, whichever indices it comes from. Each triplet has its values in ascending order, and the triplets are in ascending order too, compared by first value, then second, then third. The algorithm should run in O(n²) time and use O(1) extra space, apart from sorting and the returned triplets.
For nums = [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. The value -1 appears twice, so the triplet [-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]].
Approach: fix one number, then run two pointers
Trying every triple of indices is O(n³), too slow for 3000 numbers, and it also needs a way to discard duplicate triplets. Sorting solves both problems.
After sorting, fix the first number nums[i]. The other two must add up to -nums[i], and they lie to the right of i. That is the pair-sum problem on a sorted range, solved with two pointers: left starts just after i and right at the last index. Look at the sum of the three numbers:
- If it is less than 0, it is too small. Only a bigger value at
leftcan raise it, so moveleftright. - If it is greater than 0, move
rightleft to get a smaller value. - If it is 0, record the triplet and move both pointers inward.
Each fixed i costs O(n) for the pointer walk, and there are about n values of i, giving O(n²).
Duplicates are also easy in a sorted array, because equal values sit side by side. Skipping a first number equal to the previous one, and skipping repeated second numbers after a hit, keeps every triplet unique. The triplets also come out in the required order: the first value never decreases with i, and for one i the second value only increases as left moves right.
On [-1, 0, 1, 2, -1, -4], sorting gives [-4, -1, -1, 0, 1, 2]. With i at -4 no pair reaches 4. With i at the first -1, the pointers find [-1, -1, 2] and then [-1, 0, 1]. The second -1 is skipped because it equals its predecessor.
Step by step
- Sort
numswithsort((a, b) => a - b). Without a compare function,sortorders numbers as text, so[10, 9, 1, -1]becomes[-1, 1, 10, 9]. - Store the length in
n. - Create
resultas an emptynumber[][], one small array per triplet. - Loop
iwhilei < n - 2. The other two numbers need room to the right. - Skip repeated first numbers: if
i > 0andnums[i]equalsnums[i - 1],continue. The same first number would find the same triplets again. - Set the pointers:
leftisi + 1andrightisn - 1. - Loop while
left < right. When they meet, all pairs for thisihave been checked. - Add the three numbers into
total. - If
totalis below 0, moveleftup. - Else if it is above 0, move
rightdown. - Otherwise it is 0: push
[nums[i], nums[left], nums[right]]. The values are already ascending becausei < left < rightin a sorted array. - Move both pointers inward. Moving only one would need the other's old value again and give the same triplet.
- Skip repeated second numbers: while
left < rightandnums[left]equalsnums[left - 1], moveleftup. No matching loop is needed forright: with a bigger value atleft, an old value atrightmakes the sum too large, and the positive-total branch moves it. - Return
result.
The solution in TypeScript
class Solution {
threeSum(nums: number[]): number[][] {
nums.sort((a, b) => a - b);
const n = nums.length;
const result: number[][] = [];
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 TypeScript details:
- The compare function.
(a, b) => a - breturns a negative number whenabelongs first, which gives ascending numeric order. Values here are at most 10^5 in size, so the subtraction is exact. sortchanges the array it is called on. AfterthreeSum, the caller'snumsis sorted. For[3, 1, 2]the caller sees[1, 2, 3]afterwards. Copy first with[...nums]if that matters.- Triplets are plain arrays.
result.push([a, b, c])adds a new array of three numbers, which is whyresultis typednumber[][]. - Single-line
continue. Anifwithout braces runs just the next statement, here thecontinue.
Complexity
Time: O(n²). Sorting is O(n log n). Then each i runs a pointer walk in which left and right together move at most n steps, and the duplicate-skipping loops only move left forward within the same walk.
Space: O(1) beyond the output, apart from the space the sort uses and the triplets returned.
Edge cases and common mistakes
- Sorting without a compare function. Numbers are compared as text, so negative numbers and multi-digit numbers end up in the wrong order and the pointer logic breaks.
- Forgetting to skip duplicates. For
[0, 0, 0, 0]the result would contain[0, 0, 0]twice or more. With the skips, it appears once. - Skipping the wrong way. Comparing
nums[i]withnums[i + 1]instead ofnums[i - 1]would skip the first copy and lose triplets that use two equal values, such as[-1, -1, 2]. - Exactly three zeros.
[0, 0, 0]gives[[0, 0, 0]].[0, 1, 1]gives[]because the only triplet adds up to 2. - No triplet. The method returns an empty array, not
undefined. - Reusing an index.
leftstarts ati + 1and the loop ends whenleft < rightfails, so no index appears twice in a triplet.
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, 0, 2, 2]gives[[-2, 0, 2]].[1, 2, 3]gives[].
