Start learning free

LESSON 351 OF 679 · TWO POINTERS

Two Sum II - Input Array Is Sorted

Practice O(n)

You get an array of integers numbers, sorted from smallest to largest, and an integer target.

Find the two numbers that add up to target. Return their positions as [i, j], with i < j.

Positions count from 1, so the first number is at position 1.

The same value can appear more than once. The two numbers must be two different elements. You can't use one element twice, even if it is half of target.

Every test has exactly one such pair. Use only a constant amount of extra memory.

 

Example 1:

Input: numbers = [2,5,9,12,20], target = 25
Output: [2,5]
Explanation: 5 + 20 = 25.
The 5 is at position 2, and the 20 is at position 5.

Example 2:

Input: numbers = [-3,0,5,5,9], target = 10
Output: [3,4]
Explanation: The two 5s are at positions 3 and 4.
They are different elements, so 5 + 5 = 10 is allowed.

Example 3:

Input: numbers = [-7,-1,2,4], target = -5
Output: [1,3]
Explanation: (-7) + 2 = -5.

 

Constraints:

  • 2 to 30,000 numbers, in sorted order.
  • Each number is from -1000 to 1000.
  • target is from -1000 to 1000.
  • There is exactly one answer.

Note:

Your algorithm should run in O(n) time and use O(1) extra space. Checking every pair of numbers takes O(n2) time, too slow for the largest tests.

This is the two-pointer idea of Two Sum, without the sorting. Here the numbers arrive sorted. So the positions you find are already the answer.

STEP 1 OF 7
    Ctrl + Enter to check