Loading practice problems…
Loading your practice workspace…
Loading code editor…
5 / 29
Sign in
Algorithms/Two Pointers

Two Sum II — Input Array Is Sorted

medium25 min

Given an array of integers sorted in non-decreasing order and a target, find two elements at distinct indices whose sum equals the target. Their values may be equal.

Return their positions as [index1, index2] in ascending order, counting the first position as 1.

Example 1

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

Output[1, 2]

2 + 7 = 9. The code reads these values at indices 0 and 1. Counting from 1, they occupy positions 1 and 2, so return [1, 2].

Example 2

Inputnumbers = [2, 3, 4], target = 6

Output[1, 3]

2 + 4 = 6. These are the first and third elements, so return [1, 3].

Constraints

  • 2 ≤ numbers.length ≤ 30,000
  • Exactly one solution exists.
  • Use O(1) extra space.
Two PointersArrays