Two Sum II – Input Array Is Sorted

Two Pointers, problem 4 of 7

Two Sum II – Input Array Is Sorted

Medium

LC #167

sorted arrayopposite ends

Not attempted yet

numbers is sorted in non-decreasing order. Find the two numbers that add up to target and return their positions as [index1, index2], 1-indexed, with index1 < index2.

Exactly one valid pair exists, and you can't use the same element twice. Use only O(1) extra space.

Example 1

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

Example 2

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

Example 3

Input: numbers = [-1, 0], target = -1
Output: [1, 2]

Constraints

  • 2 ≤ len(numbers) ≤ 5 × 10⁴
  • -10⁵ ≤ numbers[i] ≤ 10⁵
  • Exactly one answer exists

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.