What is Two Sum II
The array is sorted. Find the two values that add up to target and return their 1-based indices. There is exactly one solution, and you may not use the same index twice.
4 9 2 7 11 15 1 2
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each step moves one pointer. |
| Memory | O(1) | Only the two indices are stored. |
Implementation
def two_sum(a, target):
l, r = 0, len(a) - 1
while l < r:
s = a[l] + a[r]
if s == target:
return l + 1, r + 1
if s < target:
l += 1
else:
r -= 1
return None