Skip to content
DSA Patterns
Menu
Language
Two PointersLC #1676 of 6← Previous

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Two Sum II. Input Array Is Sorted

Problem (restated)

Given a 1-indexed sorted array of integers, find two numbers that add up to target. Return their 1-based indices. Exactly one solution exists.

Intuition

Sorted order lets the larger end decrease the sum and the smaller end increase it. one pass from both ends.

Approaches

Two pointers from ends

Unverified
Time O(n)Space O(1)

Idea. lo at start, hi at end. If sum too small, lo++. If too large, hi–. Else return 1-based indices.

Walkthrough. numbers=[2,7,11,15], target=9 → 2+15 too big, 2+11 too big, 2+7=9 → [1,2].

Trade-offs. Faster than hash map when input is sorted and constant extra space is required.

Solution
export function twoSum(numbers: number[], target: number): number[] {
  let lo = 0, hi = numbers.length - 1;
  while (lo < hi) {
    const s = numbers[lo]! + numbers[hi]!;
    if (s === target) return [lo + 1, hi + 1];
    if (s < target) lo++;
    else hi--;
  }
  return [-1, -1];
}
export function twoSum(numbers: number[], target: number): number[] {
  let lo = 0, hi = numbers.length - 1;
  while (lo < hi) {
    const s = numbers[lo]! + numbers[hi]!;
    if (s === target) return [lo + 1, hi + 1];
    if (s < target) lo++;
    else hi--;
  }
  return [-1, -1];
}

Template connection

Sorted two-sum from the two ends. A pair below target moves left. A pair above target moves right. The input has exactly one answer, and the returned indexes are 1-based.

Reflection

  • The array is already sorted. Why does that make a hash map unnecessary, and where does the 1-based index off-by-one hide?
  • You cannot use the same element twice. What do you do when L and R meet?
  • Dropping in the Two Sum hash template throws away the sorted-input cue.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Sorted 1-indexed array. Pair that sums to 9. Exactly one answer.

2
0
7
1
11
2
15
3

target = 9

Key:Left / slowRight / fastMatchSettled