Menu
CoddyTech

Two Sum II: Sorted Input

You get an array of integers numbers sorted in non-decreasing order, and an integer target. Exactly one pair of different positions holds two values that add up to target. Return those two positions as 0-based indices, the smaller index first.

Function

twoSumSorted(numbers: integer-array, target: integer) → integer-array
numbersinteger-array
the sorted array of integers
targetinteger
the sum the two values must reach
Returnsinteger-array
the two 0-based indices [i, j] with i < j and numbers[i] + numbers[j] == target

Constraints

  • 2 ≤ numbers.length ≤ 104
  • -5 × 108 ≤ numbers[i] ≤ 5 × 108
  • -109 ≤ target ≤ 109
  • numbers is sorted in non-decreasing order.
  • Exactly one pair of indices i < j has numbers[i] + numbers[j] == target.

Examples

Input
numbers = [-4, 1, 3, 8, 12]target = 9
Output
[1, 3]
Explanation
1 sits at index 1 and 8 at index 3, and 1 + 8 = 9. No other pair reaches 9: for example, -4 + 12 = 8.

lock icon+13 hidden tests on Submit

challenge icon

Follow-up

Can you solve it in O(n) time with O(1) extra memory?

Reset code
def twoSumSorted(numbers, target):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

numbers = [-4, 1, 3, 8, 12]
target = 9

Expected

[1, 3]