Typorithm · medium

Two Sum II (Sorted)

two-sum-iitwo-pointerssorted-inputconvergingtarget-sum
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Two Sum II (Sorted)

0%

Two Pointers

On a sorted array, move left up when the pair sum is too small and right down when too big until it hits the target.

Because the input is sorted, the sum of the two endpoints guides the search.

If the sum is too small, only a larger left value can help, so advance left.

If too large, only a smaller right value can help, so retreat right — each step rules out a row or column of pairs.

01

Requires sorted input.

02

Sum too small → left up.

03

Sum too big → right down.

function twoSum(numbers, target) {
  let left = 0;
  let right = numbers.length - 1;

  while (left < right) {
    const sum = numbers[left] + numbers[right];
    if (sum === target) {
      return [left + 1, right + 1];
    }
    if (sum < target) {
      left += 1;
    } else {
      right -= 1;
    }
  }

  return [];
}

Read the implementation

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

1. Both ends

Start at the smallest and largest values.

let left = 0;
  let right = numbers.length - 1

2. Current pair sum

Evaluate the sum of the current endpoints.

const sum = numbers[left] + numbers[right]

3. Need bigger

Too small, so move left up to a larger value.

if (sum < target) {
      left += 1;
    }

4. 1-indexed answer

Return the found indices, converted to 1-based.

return [left + 1, right + 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.

Two Sum II (Sorted): Lesson & Practice · Typorithm | ApplyDjinn