Skip to content

Two Sum II – Input Array Is Sorted

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space.

InputTargetOutput
[2, 7, 11, 15]9[1, 2]
[2, 3, 4]6[1, 3]
[-1, 0]-1[1, 2]
  • 2 <= numbers.length <= 3 × 10^4
  • -1000 <= numbers[i] <= 1000
  • numbers is sorted in non-decreasing order
  • -1000 <= target <= 1000
  • Exactly one valid answer exists
ApproachTimeSpaceNotes
Two PointersO(n)O(1)Optimal solution, requires sorted array

* n = length of the input array

★ Recommended

Place one pointer at the start of the array and one at the end. Compute the sum of the two pointed-at values. If the sum equals the target, return the 1-indexed positions. If the sum is less than the target, advance the left pointer to increase the sum. If the sum is greater, retreat the right pointer to decrease it.

This works because the array is sorted: moving left right can only increase the sum; moving right left can only decrease it. Every step eliminates at least one element from consideration.

⏱ Time O(n) At most one pass 💾 Space O(1) Only two pointer variables

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

Stepleftrightsumaction
10 (2)3 (15)17> 9 → right--
20 (2)2 (11)13> 9 → right--
30 (2)1 (7)9== 9 → return [1, 2]

Animated walkthrough

Two pointers finding the pair in [2, 7, 11, 15] with target 9

Use Next or Autoplay to see how the left and right pointers move based on the sum comparison.

Step 1 of 3 Target: 9
Waiting to begin...
Array state
Memory / lookup state

function twoSum(numbers, target):
left, right = 0, len(numbers) - 1
while left < right:
s = numbers[left] + numbers[right]
if s == target:
return [left + 1, right + 1]
elif s < target:
left++
else:
right--
two_sum_ii_two_pointer.py
from typing import List
def two_sum(numbers: List[int], target: int) -> List[int]:
left, right = 0, len(numbers) - 1
while left < right:
s = numbers[left] + numbers[right]
if s == target:
return [left + 1, right + 1]
elif s < target:
left += 1
else:
right -= 1
return []