Problem overview
The method ThreeSum receives an int[] called nums and returns a List<int[]> of all triplets of values that add up to 0. The three values must come from three different indices, and the answer must not contain the same triplet twice, however many index choices produce it. 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]]. For {0, 1, 1} it is empty, and for {0, 0, 0, 0} it is the single triplet [0, 0, 0]. The method should run in O(n²) time.
Approach: fix one number, scan for the other two
Trying every triple of indices is O(n³), too slow for 3,000 elements. Using a set to remove duplicate triplets afterwards adds clumsy bookkeeping. The lesson uses a tidier idea built on sorting.
After sorting nums, fix the first number nums[i]. The remaining two numbers must sum to -nums[i] and lie to the right of i. Because that part of the array is sorted, two pointers can find all such pairs in one sweep: left starts just after i and right at the last index. The sum of the three values tells which pointer to move:
- A sum below 0 is too small. Only a larger value at
leftcan raise it, so moveleftright. - A sum above 0 is too large. Move
rightleft to get a smaller value. - A sum of 0 is a triplet: record it, then move both pointers inward.
One sweep is O(n) and there are n choices of i, so the total is O(n²) after the O(n log n) sort.
Sorting also makes duplicates easy to remove. Equal values sit side by side, so skipping a first number equal to the previous one and a second number equal to the previous one produces each distinct triplet once. And since i < left < right in a sorted array, every triplet comes out already in ascending order, and the triplets appear in ascending order too, so no final sort is needed.
Here is the sorted array {-4, -1, -1, 0, 1, 2} in action:
| i | left | right | sum |
|---|---|---|---|
| 0 | 1 | 5 | -3 |
| 0 | 2 | 5 | -3 |
| 0 | 3 | 5 | -2 |
| 0 | 4 | 5 | -1 |
| 1 | 2 | 5 | 0 |
| 1 | 3 | 4 | 0 |
| 3 | 4 | 5 | 3 |
For i = 0 (value -4) no pair works. For i = 1 (value -1) the sums of 0 give the triplets [-1, -1, 2] and [-1, 0, 1]. Index 2 is skipped because it repeats the value -1, and i = 3 finds nothing.
Step by step
- Sort
numswithArray.Sort. - Store the length as
nfor the loop bounds. - Create the list
resultofint[], one array per triplet. - Loop
iwhilei < n - 2. The other two numbers need two places to the right ofi. - Skip a repeated first number: if
i > 0andnums[i] == nums[i - 1],continue. The same first number would find the same triplets again. - Place the pointers:
left = i + 1,right = n - 1. - Loop while
left < right. When they meet, every pair for thisihas been checked. - Add the three values into
total. - Too small:
left++. - Too large:
right--. - Exactly zero: add
new int[] { nums[i], nums[left], nums[right] }to the result. - Move both pointers inward. Moving only one would need the other's old value again and repeat the triplet.
- Skip equal second numbers: while
left < rightandnums[left] == nums[left - 1],left++. No similar loop is needed forright: with a bigger value atleft, an unchangedrightmakes the sum too large, and the "too large" branch moves it. - Return
result.
The solution in C#
class Solution {
public List<int[]> ThreeSum(int[] nums) {
Array.Sort(nums);
int n = nums.Length;
List<int[]> result = new List<int[]>();
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(new int[] { nums[i], nums[left], nums[right] });
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
}
}
}
return result;
}
}
C# details worth knowing:
Array.Sortsorts in place. It reorders the caller's array and returns nothing. After the call on{-1, 0, 1, 2, -1, -4}, the caller's array reads{-4, -1, -1, 0, 1, 2}. Copy the array first if you need the original order.List<int[]>is a growable list whose elements are arrays.new int[] { a, b, c }creates a three-element array in one expression.Listneedsusing System.Collections.Generic;andArrayneedsusing System;in a standalone file.- Sums stay in range. Values are within plus or minus 100,000, so adding three of them fits easily in an
int. With values nearint.MaxValuethe sum could wrap silently, and alongwould be needed. continueon one line. Anifwithout braces controls only the next statement, which is fine for a singlecontinue.
Complexity
Time: O(n²). Sorting costs O(n log n). Each value of i then runs a two-pointer sweep in which left and right together move at most n steps.
Space: O(1) extra, apart from the sort's own working space and the returned triplets.
Edge cases and common mistakes
- All zeros.
{0, 0, 0, 0}returns one triplet,[0, 0, 0]. The duplicate skips stop the other index choices from adding it again. - Exactly three elements.
{0, 0, 0}gives[[0, 0, 0]]:i = 0is the only first number. - No answer.
{0, 1, 1}gives an empty list. - Repeated values in a triplet.
{-2, 0, 1, 1, 2}gives[[-2, 0, 2], [-2, 1, 1]]. The repeated 1 is allowed within a triplet, only a repeated triplet is not. - Skipping duplicates too early. Comparing
nums[i]withnums[i + 1]would throw away a valid triplet such as[-1, -1, 2]. Comparing with the previous element lets the first copy be used. - Not sorting first. The pointer moves rely on order, and without it the duplicate skipping does not work.
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]].{0, 0, 0}gives[[0, 0, 0]].
