Problem overview
The method threeSum receives an int[] nums and returns a List<List<Integer>> of all triplets [nums[i], nums[j], nums[k]] that add up to 0, where i, j and k are three different indices. The answer must not contain the same triplet twice, whichever indices it came from. Each triplet is written in ascending order and the triplets are listed in ascending order as well.
For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. Three different index choices give the values -1, 0, 1 or -1, -1, 2, but only two distinct triplets exist. For [0, 0, 0, 0] many index choices give 0 + 0 + 0, yet the answer is the single triplet [[0, 0, 0]]. For [0, 1, 1] the answer is the empty list.
Approach: fix one number, then run two pointers
The brute force tries every triple of indices: three nested loops, O(n³) time. With up to 3000 numbers that is billions of checks. It also needs extra work to throw away repeated triplets.
Sorting nums first changes the problem in two ways:
- Equal values sit side by side, so repeats are easy to skip.
- For a fixed first number, the other two can be found with two pointers. Put
leftjust after it andrightat the end. If the sum is too small, only movingleftright can raise it. If it is too large, only movingrightleft can lower it.
The sort costs O(n log n), and the pointer scan for each first number costs O(n), so the total is O(n²). Since the array is scanned from left to right in sorted order, every triplet comes out with nums[i] <= nums[left] <= nums[right] and the triplets arrive already in the order the statement asks for, so no sort of the result is needed.
Here is the scan for the sorted array [-4, -1, -1, 0, 1, 2]:
| i | left | right | total | Action |
|---|---|---|---|---|
| 0 | 1 | 5 | -3 | too small: left moves |
| 0 | 2 | 5 | -3 | too small: left moves |
| 0 | 3 | 5 | -2 | too small: left moves |
| 0 | 4 | 5 | -1 | too small: left moves, the pointers meet |
| 1 | 2 | 5 | 0 | found [-1, -1, 2] |
| 1 | 3 | 4 | 0 | found [-1, 0, 1] |
| 2 | - | - | - | skipped: same value as index 1 |
| 3 | 4 | 5 | 3 | too large: right moves, the pointers meet |
Step by step
- Sort.
Arrays.sort(nums)sorts the array in ascending order, in place. - Store the length in
n, and create the emptyresultlist, aList<List<Integer>>holding a newArrayList. Each element of it is itself a list of three numbers. - Choose the first number. Loop
ifrom 0 whilei < n - 2. The other two numbers lie to the right ofi, so it stops two places before the end. - Skip repeated first numbers. If
i > 0andnums[i] == nums[i - 1],continue. The same first number would find the same triplets again. - Place the pointers.
left = i + 1andright = n - 1. - Loop while
left < right. When they meet, every pair for thisihas been checked. - Compute
totalasnums[i] + nums[left] + nums[right]. - Too small or too large. If
total < 0, doleft++. Iftotal > 0, doright--. - Found one. Otherwise
totalis 0, so add the triplet withArrays.asList(nums[i], nums[left], nums[right]). Its values are already ascending, becausei < left < rightin a sorted array. - Move both pointers inward. Keeping one in place would need the other one's old value to reach 0 again, which gives the same triplet.
- Skip repeated second numbers. While
left < rightandnums[left] == nums[left - 1], doleft++. No loop is needed forright: with a bigger value atleft, an old value atrightmakes the total positive, and thetotal > 0branch moves it. - Return
result.
The solution in Java
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
List<List<Integer>> result = new ArrayList<>();
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.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
}
}
}
return result;
}
}
The Java details worth a closer look:
Arrays.sortchanges the caller's array. The method sortsnumsin place, so after the call,[-1, 0, 1, 2, -1, -4]reads[-4, -1, -1, 0, 1, 2]. That is acceptable here, since the method returns only the triplets. To keep the original order, sort a copy made withArrays.copyOf.Arrays.asList(a, b, c)and boxing. The threeintvalues are autoboxed intoIntegerobjects and wrapped in a fixed-size list. Callingaddon one of those triplets throwsUnsupportedOperationException. Reading, which is all the answer needs, works normally.- Several variables in one declaration.
int left = i + 1, right = n - 1;declares both in one statement. - One-line
if.if (i > 0 && nums[i] == nums[i - 1]) continue;works without braces. Because&&short-circuits,nums[i - 1]is never read wheniis 0. - Comparing values.
nums[i] == nums[i - 1]comparesintvalues, so==is correct. It would not be for twoIntegerobjects, which should be compared withequals. - Overflow. The values stay within plus or minus 100,000, so the sum of three can never overflow an
int.
Complexity
Time: O(n²). Sorting is O(n log n). For each of the at most n values of i, the pointers together move at most n steps, because each step moves one of them toward the other. That is O(n) per i and O(n²) overall, which dominates the sort.
Space: O(1) extra, apart from the sort's own working space and the triplets that are returned.
Edge cases and common mistakes
- Nothing found.
[0, 1, 1]and[1, 2, 3]give[], an empty list, notnull. - All zeros.
[0, 0, 0, 0]gives one triplet. The first number is used once, and the pointers then meet. - Forgetting to skip repeated first numbers. On
[-1, -1, 0, 1, 2]the answer becomes[[-1, -1, 2], [-1, 0, 1], [-1, 0, 1]], with[-1, 0, 1]twice. With the skip, it is[[-1, -1, 2], [-1, 0, 1]]. - Skipping the wrong way. Comparing
nums[i]withnums[i + 1]instead ofnums[i - 1]would drop triplets that use two equal values, such as[-1, -1, 2]. Comparing with the previous value skips only the repeats of a first number already tried. - Repeated values in the middle.
[-2, 0, 0, 2, 2]gives[[-2, 0, 2]]: the two 0s and the two 2s would otherwise give the same triplet again. - Starting
leftat 0. The pointer must begin right afteri. Otherwise a number could pair with itself or with an earlier first number, repeating combinations.
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]].[-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]].
