Two Pointers & Sliding Window
Given an array of integers, find all unique triplets [a,b,c] such that a + b + c = 0. The output must not contain duplicate triplets.
Three nested loops with a Set to dedupe triplets works, but it's O(n³) and the dedupe step is clunky. Sorting the array first unlocks something better: fix one number, then use the two-pointer technique on the remaining two — since the array is sorted, you can slide left/right pointers toward each other based on whether the current sum is too big or too small, exactly like Two Sum on a sorted array. Sorting also makes skipping duplicate values trivial, since equal values end up adjacent.
// Given an array of integers, find all unique triplets that sum to
// zero. No duplicate triplets in the output.
// --- Brute force: three nested loops, dedupe with a Set of sorted keys ---
function threeSumBrute(nums) {
const results = new Set();
const n = nums.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
if (nums[i] + nums[j] + nums[k] === 0) {
const triplet = [nums[i], nums[j], nums[k]].sort((a, b) => a - b);
results.add(JSON.stringify(triplet));
}
}
}
}
return [...results].map((s) => JSON.parse(s));
}
// --- Optimal: sort once, fix one number, two-pointer the rest ---
// Sorting lets us skip duplicates cheaply and use the two-pointer
// pattern (see two-pointers.js) on the remaining two numbers.
function threeSum(nums) {
const sorted = [...nums].sort((a, b) => a - b);
const results = [];
for (let i = 0; i < sorted.length - 2; i++) {
if (i > 0 && sorted[i] === sorted[i - 1]) continue; // skip duplicate anchors
let left = i + 1;
let right = sorted.length - 1;
while (left < right) {
const sum = sorted[i] + sorted[left] + sorted[right];
if (sum === 0) {
results.push([sorted[i], sorted[left], sorted[right]]);
left++;
right--;
while (left < right && sorted[left] === sorted[left - 1]) left++; // skip dupes
while (left < right && sorted[right] === sorted[right + 1]) right--;
} else if (sum < 0) {
left++; // need a bigger sum
} else {
right--; // need a smaller sum
}
}
}
return results;
}
// --- Example Usage ---
console.log(threeSum([-1, 0, 1, 2, -1, -4]));
// [[-1,-1,2], [-1,0,1]]
console.log(threeSumBrute([-1, 0, 1, 2, -1, -4]));
// same triplets, unordered