Three sum
Find every group of three numbers that adds up to 0: sort, fix one number, then close in on the other two with two pointers.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
3Sum is the two-pointer pair sum run once for every first number. (1) Sort. (2) Fix a[i] as the first number: the other two must add up to -a[i], and they must come from the numbers to its right. (3) Put l at the left end and r at the right end of that part. A sum below 0 means we need something bigger, so move l right; a sum above 0 means we need something smaller, so move r left. This is only safe because the numbers are sorted. (4) Repeat for every i, skipping repeated values so the same triplet is never listed twice.
Code
public static List<(int, int, int)> ThreeSum(int[] a) {
Array.Sort(a);
var res = new List<(int, int, int)>();
for (int i = 0; i < a.Length - 2; i++) {
if (i > 0 && a[i] == a[i - 1]) continue;
int l = i + 1, r = a.Length - 1;
while (l < r) {
int sum = a[i] + a[l] + a[r];
if (sum == 0) {
res.Add((a[i], a[l], a[r]));
l++; r--;
while (l < r && a[l] == a[l - 1]) l++;
} else if (sum < 0) l++;
else r--;
}
}
return res;
}static List<int[]> threeSum(int[] a) {
Arrays.sort(a);
List<int[]> res = new ArrayList<>();
for (int i = 0; i < a.length - 2; i++) {
if (i > 0 && a[i] == a[i - 1]) continue;
int l = i + 1, r = a.length - 1;
while (l < r) {
int sum = a[i] + a[l] + a[r];
if (sum == 0) {
res.add(new int[]{a[i], a[l], a[r]});
l++; r--;
while (l < r && a[l] == a[l - 1]) l++;
} else if (sum < 0) l++;
else r--;
}
}
return res;
}vector<array<int, 3>> threeSum(vector<int>& a) {
sort(a.begin(), a.end());
vector<array<int, 3>> res;
for (int i = 0; i < (int)a.size() - 2; i++) {
if (i > 0 && a[i] == a[i - 1]) continue;
int l = i + 1, r = (int)a.size() - 1;
while (l < r) {
int sum = a[i] + a[l] + a[r];
if (sum == 0) {
res.push_back({a[i], a[l], a[r]});
l++; r--;
while (l < r && a[l] == a[l - 1]) l++;
} else if (sum < 0) l++;
else r--;
}
}
return res;
}def three_sum(a: list[int]) -> list[tuple[int, int, int]]:
a.sort()
res = []
for i in range(len(a) - 2):
if i > 0 and a[i] == a[i - 1]: continue
l, r = i + 1, len(a) - 1
while l < r:
total = a[i] + a[l] + a[r]
if total == 0:
res.append((a[i], a[l], a[r]))
l += 1; r -= 1
while l < r and a[l] == a[l - 1]: l += 1
elif total < 0: l += 1
else: r -= 1
return resTips
- Why move l when the sum is too small? r already holds the biggest number still available, so only a bigger l can raise the sum. The same reasoning, mirrored, tells you to move r when the sum is too big.
- Skipping repeats: a repeated first number (i) or a repeated l would just rediscover a triplet that is already in the list.
- Faded numbers in the picture are out of play: used as an earlier first number, or passed by a pointer.
In the .NET library
O(n²) is as good as it gets with plain comparisons: n choices for the first number, and each pair search is O(n). A hash-based version has the same cost but needs extra care to avoid duplicate triplets.