function threeSum(nums) {nums.sort((a, b) => a - b);◄
const res = [];
for (let i = 0; i < nums.length - 2; i++) {if (i > 0 && nums[i] === nums[i-1]) continue;
let left = i + 1, right = nums.length - 1;
while (left < right) {const sum = nums[i] + nums[left] + nums[right];
if (sum < 0) left++;
else if (sum > 0) right--;
else {res.push([nums[i], nums[left], nums[right]]);
left++; right--;
while (left<right && nums[left]===nums[left-1]) left++;
while (left<right && nums[right]===nums[right+1]) right--;
}
}
}
return res;
}
Sorting unlocks the two-pointer trick and makes duplicate-skipping easy, at a cost of only O(n log n).
Fix one number as an anchor (nums[i]); the problem reduces to “find two numbers in the rest that sum to −nums[i]” — the classic sorted two-pointer scan.
With left just after the anchor and right at the end: if the sum is too small move left up (bigger), if too big move right down (smaller), if exactly zero record it.
Skip duplicate values for the anchor and after finding a triplet, so each combination is reported once. Overall O(n²).