Two Sum II - Input Array Is Sorted

Medium

Topics
ArrayTwo PointersBinary Search

Given a 1-indexed array numbers sorted in non-decreasing order, find two numbers adding up to target. Return [index1, index2] (1-indexed) with index1 < index2.

Exactly one solution exists; use only constant extra space.

Example 1

20left71112153
Found at indices [1, 2] (the answer is 1-based here).
Cells are the array values; the small numbers underneath are indices.
Input:  numbers = [2,7,11,15], target = 9
Output: [1,2]

Example 2

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

Constraints

  • 2 <= numbers.length <= 3*10^4
  • numbers is sorted non-decreasing.
  • Exactly one solution.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Because the array is sorted, the sum of the two ends tells us which direction to move. If the pair is too small, only a larger left value helps; if too big, only a smaller right value helps.

A two-pointer sweep exploits this to reach the answer in one pass and O(1) space, beating both brute force and the hash-map approach.

Approach

  1. Put l at the first index and r at the last.
  2. Compute s = numbers[l] + numbers[r].
  3. If s == target, return the 1-based indices [l+1, r+1].
  4. If s < target, increment l (need a bigger number). If s > target, decrement r.

Walkthrough

numbers = [2, 7, 11, 15], target = 9

l=0 r=3  2+15=17 > 9  -> r=2
l=0 r=2  2+11=13 > 9  -> r=1
l=0 r=1  2+7 =9  == 9 -> return [1, 2]

Complexity

  • Time — O(n): each iteration moves one pointer inward, so together they cross the array at most once.
  • Space — O(1): only two index variables.

Common Pitfalls

  • This works only because the array is sorted — do not use it on unsorted input.
  • The problem is 1-indexed, so add 1 to each pointer.

Full Solution — all languages

class Solution:
    def twoSum(self, numbers, target):
        lo, hi = 0, len(numbers) - 1
        while lo < hi:
            s = numbers[lo] + numbers[hi]
            if s == target:
                return [lo + 1, hi + 1]
            if s < target:
                lo += 1
            else:
                hi -= 1
        return []
SensAI
Beta
Tap the mic to stop voice mode