Two Sum II

Difficulty: Easy

Problem

You are given a sorted array of numbers and a target. Find two different numbers whose sum equals the target and return their indices using 1-based indexing.

Example

Input: numbers = [2, 3, 4, 7, 11], target = 10
Output: [2, 4]
Explanation: 3 + 7 = 10, so return [2, 4] (1-based indices).

Brute-force approach

Check every possible pair and see if their sum equals the target.

Steps

  1. For each i, try every j > i
  2. If numbers[i] + numbers[j] == target, return [i+1, j+1]
  3. If no pair found, return no solution

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

Trade-offs

  • Too slow for large arrays
  • Doesn't use the sorted property

Optimal approach

Key insight: Because the array is sorted, moving the pointers changes the sum in a predictable way: moving left to the right always increases (or keeps) the left value, so the sum can only go up; moving right to the left always decreases (or keeps) the right value, so the sum can only go down.

Use Two Pointers to leverage the sorted array and find the answer in one pass.

Steps

  1. Initialize left = 0 and right = n - 1
  2. Compute sum = numbers[left] + numbers[right]
  3. If sum == target, return [left + 1, right + 1]
  4. If sum < target, move left forward
  5. If sum > target, move right backward

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