Three sum
On a sorted array, fix one value and use two pointers to find pairs that cancel it out to zero.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Sort first, then fix the smallest number of a triplet and run the two-pointer pair-sum search for "add up to -a[i]" on the rest of the array. Sorting also makes duplicate triplets sit next to each other so they are easy to skip.
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--; }
else if (sum < 0) l++;
else r--;
}
}
return res;
}Tips
- Skip a repeated value for i: using the same first number again would only rediscover a triplet already found.
- This is the natural next step after two-pointer pair sum: the same l/r closing-in idea, run once per fixed index.
In the .NET library
The O(n²) here is as good as it gets with plain comparisons; a hash-based variant can find pairs faster but still needs care to avoid duplicate triplets.