←
Lens · Two Pointers · Sorted input

Two numbers that add up to a target

10
31
42
63
84
115
nums[l] + nums[r]
–
target
10
The goalFind two numbers that add up to 10. The list is sorted.
1 / 12

Code

O(n) time · O(1) space
1def pair_sum(nums, target):2    l, r = 0, len(nums) - 13    while l < r:4        s = nums[l] + nums[r]5        if s == target:6            return [l, r]7        if s < target:8            l += 19        else:10            r -= 111    return []
WHY IT WORKSThe list is sorted, so a small sum can only grow by moving left up, and a big sum can only shrink by moving right down.