Two Sum II - Input Array Is Sorted
Master this topic with zero to advance depth.
Two Sum II - Input Array Is Sorted
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. Return the indices of the two numbers, [index1, index2], added by one.
Visual Representation
numbers = [2, 7, 11, 15], target = 9
L: index 0 (val 2)
R: index 3 (val 15)
Sum = 2 + 15 = 17 (> 9) -> Move R left (R=2)
L: index 0 (val 2)
R: index 2 (val 11)
Sum = 2 + 11 = 13 (> 9) -> Move R left (R=1)
L: index 0 (val 2)
R: index 1 (val 7)
Sum = 2 + 7 = 9 (== 9) -> FOUND! [1, 2] (1-indexed)Examples
The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Level I: Brute Force (Check All Pairs)
Intuition
Try every possible pair of numbers to see if they sum up to the target. While correct, it doesn't leverage the fact that the array is sorted.
Detailed Dry Run
| i | j | nums[i] | nums[j] | Sum | Target | Match? |
|---|---|---|---|---|---|---|
| 0 | 1 | 2 | 7 | 9 | 9 | YES! Return [1, 2] |
⚠️ Common Pitfalls & Tips
O(N^2) complexity is inefficient for large arrays.
Level II: Binary Search
Intuition
For each element at index i, we know the required second element is target - numbers[i]. Since the array is sorted, we can use binary search to find this complement in the sub-array to the right of i (numbers[i+1...n-1]).
Detailed Dry Run
Input: [2, 7, 11, 15], Target: 9
i = 0 (2): Search for9 - 2 = 7in[7, 11, 15].- Binary Search found
7at index 1. - Return
[1, 2].
⚠️ Common Pitfalls & Tips
While better than O(N^2), it is still worse than the O(N) Two Pointer approach.
Level III: Optimal (Two Pointer Collision)
Intuition
Since the array is sorted, we can start with two pointers at the extreme ends. If the sum is too small, we move the left pointer right (to increase values). If the sum is too large, we move the right pointer left (to decrease values). This is guaranteed to find the solution in one pass.
Detailed Dry Run
Input: [2, 7, 11, 15], Target: 9
| L | R | Sum | Action |
|---|---|---|---|
| 0 (2) | 3 (15) | 17 | Sum > 9, move R left (R--) |
| 0 (2) | 2 (11) | 13 | Sum > 9, move R left (R--) |
| 0 (2) | 1 (7) | 9 | Sum == 9, RETURN [1, 2] |
⚠️ Common Pitfalls & Tips
Ensure 1-based indexing. This approach only works on sorted arrays.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.