The problem, in one line. Given a list already sorted from small to large, return the two positions, counting from 1, whose numbers add to the target, using only constant extra space. LeetCode 167.
The tell. Sorted input plus a pair to find. Sorted means a sum that is too big or too small points at exactly one marker to move.
The wrong first idea
Reach for the hash map from the unsorted Two Sum.
seen = {}
for i, x in enumerate(numbers):
if target - x in seen:
return [seen[target - x] + 1, i + 1]
seen[x] = i
It is correct and O(n) in time. It ignores the one fact the statement hands you, that the list is sorted, and it spends O(n) memory when the problem asks for constant space.
The invariant
Start with a marker on the smallest number and one on the largest. Add them. Too small means the left number is too small to ever work, so move it right. Too big means the right number is too big, so move it left.
[2, 7, 11, 15] target 9
2 + 15 = 17 too big, drop 15. 2 + 11 = 13 too big, drop 11. 2 + 7 = 9 found.
The sentence that stays true every step: if an answer exists, it lies between the two markers. Each move throws away a number that cannot pair with anything left.
The solution
def two_sum(numbers, target):
i, j = 0, len(numbers) - 1
while i < j:
s = numbers[i] + numbers[j]
if s == target:
return [i + 1, j + 1]
if s < target:
i += 1 # sum too small: only a bigger left value can help
else:
j -= 1 # sum too big: only a smaller right value can help
return []
print(two_sum([2, 7, 11, 15], 9))
print(two_sum([1, 3, 4, 5, 7, 10, 11], 9))
print(two_sum([-3, 0, 3], 0))
[1, 2]
[3, 4]
[1, 3]
func twoSum(numbers []int, target int) []int {
i, j := 0, len(numbers)-1
for i < j {
s := numbers[i] + numbers[j]
if s == target {
return []int{i + 1, j + 1}
}
if s < target {
i++ // sum too small: only a bigger left value can help
} else {
j-- // sum too big: only a smaller right value can help
}
}
return nil
}
Same calls print [1 2], [3 4], [1 3].
Complexity
- Time O(n): each step moves one marker inward, so at most n steps.
- Space O(1): two indices and a sum.
Traps
- Looping while
i <= j. On[1, 2]with target 2 the markers meet and the answer is[1, 1], one number used twice. - Returning zero-based positions. The statement counts from 1, so
[2, 7, 11, 15]with target 9 must give[1, 2], not[0, 1]. - Moving both markers on a miss. On
[2, 7, 11, 15]with target 9 the first sum is 17, both move, and the pair2, 7is never tried. The loop returns nothing.
Next in the ladder
3sum needs three numbers, so you fix one and run this exact pair search on everything to its right.