Two Sum II - Input Array Is Sorted - Problem

You're given a sorted array of integers and need to find two numbers that add up to a specific target. This is a classic problem that tests your ability to leverage the sorted property of the input.

Given a 1-indexed array numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 โ‰ค index1 < index2 โ‰ค numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

Key constraints:

  • The tests guarantee that there is exactly one solution
  • You may not use the same element twice
  • Your solution must use only constant extra space

Example: If numbers = [2,7,11,15] and target = 9, return [1,2] because numbers[1] + numbers[2] = 2 + 7 = 9.

Input & Output

example_1.py โ€” Basic Case
$ Input: numbers = [2,7,11,15], target = 9
โ€บ Output: [1,2]
๐Ÿ’ก Note: The sum of 2 and 7 is 9. Since we are looking for 1-indexed positions, we return [1,2].
example_2.py โ€” Middle Elements
$ Input: numbers = [2,3,4], target = 6
โ€บ Output: [1,3]
๐Ÿ’ก Note: The sum of 2 and 4 is 6. The 1-indexed positions are [1,3].
example_3.py โ€” Adjacent Elements
$ Input: numbers = [-1,0], target = -1
โ€บ Output: [1,2]
๐Ÿ’ก Note: The sum of -1 and 0 is -1. The 1-indexed positions are [1,2].

Visualization

Tap to expand
271115LeftRightTarget = 92 + 15 = 17 > 9 โ†’ Move Right pointer left7117 + 11 = 18 > 9 โ†’ Move Right pointer left again272 + 7 = 9 โœ“ Found!Return [1, 2]
Understanding the Visualization
1
Setup
Place one pointer at the smallest element (left) and another at the largest (right)
2
Calculate
Add the values at both pointers and compare with target
3
Adjust
If sum is too small, move left pointer right (increase). If too large, move right pointer left (decrease)
4
Success
When sum equals target, we've found our answer!
Key Takeaway
๐ŸŽฏ Key Insight: The sorted property allows us to make intelligent decisions about which pointer to move, converging to the solution in linear time without extra space!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

We potentially check every pair of elements, leading to nร—(n-1)/2 comparisons

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using a few variables, no additional data structures

n
2n
โœ“ Linear Space

Constraints

  • 2 โ‰ค numbers.length โ‰ค 3 * 104
  • -1000 โ‰ค numbers[i] โ‰ค 1000
  • -1000 โ‰ค target โ‰ค 1000
  • The array is sorted in non-decreasing order
  • Exactly one solution exists
  • You cannot use the same element twice
Asked in
Amazon 67 Google 45 Microsoft 38 Meta 29
89.7K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen