Two Sum II - Input Array Is Sorted

Medium#167towards each other

You get numbers sorted from smallest to largest and a target sum. Find two numbers that add up to it and return their positions, counting from 1, not from 0. A pair always exists, and one number cannot be taken twice. Our example: [1, 4, 6, 7, 10, 13], sum 16 — the answer is [3, 5]: 6 + 10.

input
numbers: integers sorted in non-decreasing order; target: an integer.
returns
The positions of the two numbers that add up to target, counted from 1: [index1, index2] with index1 < index2.
constraints
  • 2 ≤ numbers.length ≤ 1000
  • −1000 ≤ numbers[i] ≤ 1000
  • numbers is sorted in non-decreasing order
  • −1000 ≤ target ≤ 1000
  • exactly one pair adds up to target
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
function twoSum(numbers, target) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.