Two Sum on a Sorted Array

MediumTwo PointersBinary Search

You are given an array of integers numbers sorted in non-decreasing order and an integer target.

Return the 0-based indices [i, j] (with i < j) of the two numbers that add up to target.

Each input has exactly one solution, and you may not use the same element twice. Use only constant extra space.

Constraints

  • 2 <= numbers.length <= 3 * 10^4
  • -1000 <= numbers[i] <= 1000, sorted ascending
  • Exactly one valid answer exists.

Examples

Example 1

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

numbers[0] + numbers[1] = 2 + 7 = 9.

Example 2

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

2 + 4 = 6.

Example 3

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

JavaScript you'll use: Arrays: create, read, update Destructuring, spread and rest

/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
function twoSumSorted(numbers, target) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.