Two Sum II - Input Array Is Sorted - Problem

Given a 1-indexed array of integers 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.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

Input & Output

Example 1 — Basic Case
$ Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
💡 Note: numbers[1] + numbers[2] = 2 + 7 = 9, so return indices [1,2] in 1-indexed format
Example 2 — Later Position
$ Input: numbers = [2,3,4], target = 6
Output: [1,3]
💡 Note: numbers[1] + numbers[3] = 2 + 4 = 6, indices are [1,3] in 1-indexed format
Example 3 — Minimum Size
$ Input: numbers = [-1,0], target = -1
Output: [1,2]
💡 Note: numbers[1] + numbers[2] = -1 + 0 = -1, return [1,2] for minimum array size

Constraints

  • 2 ≤ numbers.length ≤ 3 × 104
  • -1000 ≤ numbers[i] ≤ 1000
  • numbers is sorted in non-decreasing order
  • -1000 ≤ target ≤ 1000
  • The tests are generated such that there is exactly one solution

Visualization

Tap to expand
Two Sum II - Input Array Is Sorted INPUT Sorted Array (1-indexed): 2 idx 1 7 idx 2 11 idx 3 15 idx 4 Target = 9 Input Values: numbers = [2,7,11,15] target = 9 Find i,j: nums[i]+nums[j]=target ALGORITHM STEPS 1 Initialize Hash Map map = {} (value --> index) 2 Process num=2 (idx 1) complement=9-2=7, not found map: {2:1} 3 Process num=7 (idx 2) complement=9-7=2 2 found in map! idx=1 4 Return Result return [map[2], 2] = [1, 2] Hash Map State Value Index (1-based) 2 1 7+2=9 [OK] Match Found! FINAL RESULT Found Two Numbers: 2 index 1 + 7 index 2 = 9 (target) Output: [1, 2] [OK] Solution Verified! numbers[1] = 2 numbers[2] = 7 2 + 7 = 9 = target Key Insight: Hash Map for O(n) Lookup The Hash Map stores each number's value as key and its index as value. For each element, we check if (target - current) exists in the map. This gives O(n) time with O(n) space. Note: Two-pointer approach uses O(1) space for sorted arrays, but Hash Map works for unsorted too. TutorialsPoint - Two Sum II - Input Array Is Sorted | Hash Map Approach
Asked in
Amazon 45 Microsoft 38 Apple 32 Google 28
185.0K 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