Two Sum II – Sorted Input
Difficulty: Medium · Pattern: Two Pointers · LeetCode #167
numbers is sorted in non-decreasing order. Find two different positions whose values add up to target and return them as 1-based indices [i, j] with i < j. Exactly one solution exists. Use only O(1) extra space.
Examples
text
numbers = [1, 3, 4, 6, 8, 11], target = 10 → [3, 4] (4 + 6)
numbers = [-5, -2, 0, 7], target = -7 → [1, 2]Hints
- The hash-map approach from Two Sum works but uses O(n) space. Use the sorted order instead.
- Start with the smallest and largest values. If their sum is too small, which pointer should move?
Approach
Place l at the start and r at the end. If numbers[l] + numbers[r] equals the target, return [l+1, r+1]. If the sum is too small, the smallest value numbers[l] can't pair with anything (every partner is ≤ numbers[r]), so do l += 1. If it's too big, numbers[r] is useless, so do r -= 1. Each step discards one element: O(n).
Complexity
Time: O(n). Space: O(1).
Python solution
def twoSum(numbers, target):
l, r = 0, len(numbers) - 1
while l < r:
s = numbers[l] + numbers[r]
if s == target:
return [l + 1, r + 1]
if s < target:
l += 1
else:
r -= 1
return []JavaScript solution
function twoSum(numbers, target) {
let l = 0, r = numbers.length - 1;
while (l < r) {
const s = numbers[l] + numbers[r];
if (s === target) return [l + 1, r + 1];
if (s < target) l++; else r--;
}
return [];
}