Two Sum II - Input Array Is Sorted

Difficulty: Medium

Given a list of numbers sorted in increasing order and a target, find two different numbers that add up to the target and return their positions.

Unlike the usual Two Sum, positions start at 1, not 0. There is always exactly one valid pair, and you can't use the same element twice. Since the list is sorted, solve it using only constant extra space.

Examples

Input: numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]

numbers[0] + numbers[1] = 2 + 7 = 9, and using 1-based positions that's [1, 2].

Input: numbers = [2, 3, 4], target = 6
Output: [1, 3]

2 + 4 = 6, which are positions 1 and 3.

Input: numbers = [-1, 0], target = -1
Output: [1, 2]

Constraints

  • 2 <= numbers.length <= 3 * 10^4

  • -1000 <= numbers[i] <= 1000

  • numbers is sorted in non-decreasing order.

  • Exactly one valid answer exists.

Approach

Because the list is sorted, moving the left pointer forward can only increase the sum, and moving the right pointer back can only decrease it. So you always know which pointer to move and never need to backtrack.

Start with pointers at the first and last numbers:

  • Sum too small: move the left pointer forward (to a bigger number).
  • Sum too big: move the right pointer back (to a smaller number).
  • Sum matches: you're done.

This takes one pass and no extra memory beyond the two pointers.

Solutions

Brute Force — Check Every Pair

Try every pair and check whether it sums to the target. Correct, but it ignores the sorted order.

function twoSum(numbers, target) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = i + 1; j < numbers.length; j++) {
      if (numbers[i] + numbers[j] === target) {
        return [i + 1, j + 1];
      }
    }
  }
  return [];
}

Time: O(n²) · Space: O(1)

Hash Map

Walk the list once. For each number, check a Map to see if the value that completes the pair was already seen. Faster than brute force, but it ignores the sorted order and uses O(n) extra memory.

function twoSum(numbers, target) {
  const seen = new Map(); // value -> index

  for (let i = 0; i < numbers.length; i++) {
    const complement = target - numbers[i];
    if (seen.has(complement)) {
      return [seen.get(complement) + 1, i + 1];
    }
    seen.set(numbers[i], i);
  }

  return [];
}

Time: O(n) · Space: O(n)

Optimal — Two Pointers

Use the sorted order directly. Start a pointer at each end. Move the left one forward if the sum is too small, or the right one back if it's too big.

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];
    } else if (sum < target) {
      left++;
    } else {
      right--;
    }
  }

  return [];
}

Time: O(n) · Space: O(1)