Typorithm · medium

3Sum

three-sumtwo-pointerssort-then-scandedupefixed-plus-pair
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn 3Sum

0%

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.

01

Sort numerically with (a, b) => a - b.

02

Fix i, two-pointer left/right.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Numeric sort

JS sort is lexicographic by default; (a, b) => a - b sorts numerically.

nums.sort((a, b) => a - b)

2. Skip duplicate anchor

Avoid repeating triplets from a duplicate fixed value.

if (i > 0 && nums[i] === nums[i - 1]) {
      continue;
    }

3. Fixed plus pair

Fix nums[i], then two-pointer the rest for the remaining sum.

const sum = nums[i] + nums[left] + nums[right]

4. Skip duplicate pair

After a hit, skip repeated left values to avoid duplicate triplets.

while (left < right && nums[left] === nums[left - 1]) {
          left += 1;
        }

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

3Sum: Lesson & Practice · Typorithm | ApplyDjinn