1. Numeric sort
JS sort is lexicographic by default; (a, b) => a - b sorts numerically.
nums.sort((a, b) => a - b)Typorithm · medium
Step 1 of 8 · intro card
Two Pointers
Sort, fix each number, then two-pointer the rest for the negation — skipping duplicates to keep triplets unique.
3Sum reduces to: fix one number, then find a pair in the rest summing to its negation.
Sorting enables the converging two-pointer scan and makes duplicate-skipping straightforward.
Skip a duplicate fixed value and duplicate pair values so each triplet appears only once.
Sort numerically with (a, b) => a - b.
Fix i, two-pointer left/right.
Skip duplicates at i and after hits.
function threeSum(nums) {
nums.sort((a, b) => a - b);
const result = [];
for (let i = 0; i < nums.length - 2; i += 1) {
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
left += 1;
} else if (sum > 0) {
right -= 1;
} else {
result.push([nums[i], nums[left], nums[right]]);
left += 1;
right -= 1;
while (left < right && nums[left] === nums[left - 1]) {
left += 1;
}
}
}
}
return result;
}Connect each part of the code to the concept before you type.
JS sort is lexicographic by default; (a, b) => a - b sorts numerically.
nums.sort((a, b) => a - b)Avoid repeating triplets from a duplicate fixed value.
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}Fix nums[i], then two-pointer the rest for the remaining sum.
const sum = nums[i] + nums[left] + nums[right]After a hit, skip repeated left values to avoid duplicate triplets.
while (left < right && nums[left] === nums[left - 1]) {
left += 1;
}Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.