Sorted Array

Two Sum II — Input Array Is Sorted

Medium
Solve it on LeetCode ↗

The problem

In a 1-indexed sorted array, find the two numbers summing to a target and return their indices. Exactly one solution exists; use O(1) extra space.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Set left = 0, right = n − 1.
  2. 2While left < right: compute sum = nums[left] + nums[right].
  3. 3sum === target → return [left + 1, right + 1] (1-indexed).
  4. 4sum < target → left++; sum > target → right−−.

Key insight

Each comparison PERMANENTLY discards one element: if the smallest+largest is too small, the smallest can pair with nothing — that invariant is why two pointers cannot miss the answer.

The solution

Watch out for

  • The answer is 1-indexed — a rare requirement that catches autopilot submissions.
  • Using a hash map works but ignores the sorted property and the O(1)-space constraint.