Algorithms · Two pointers
Two Sum II: the input is sorted
The list is sorted: find the pair that adds up to the target.
The problem
Same as Two Sum, but the numbers are sorted from small to big. Return the two positions (counting from 0) whose numbers add up to target. Use the order to avoid checking every pair. (LeetCode counts positions from 1 in this one.)
pair_sum_sorted([2, 7, 11, 15], 9)→[0, 1]pair_sum_sorted([2, 3, 4], 6)→[0, 2]Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def pair_sum_sorted(nums, target):take sorted numbers and a target for i in range(len(nums)):pick a first number for j in range(i + 1, len(nums)):try every number after it if nums[i] + nums[j] == target:do they add up? return [i, j]hand back both positionsNow ask: what if there were a billion?
Google’s LevelDB keeps data in sorted files and merges them by walking two fingers forward through two files at once, never jumping back. That’s how it handles billions of keys on one disk.
Aim for O(n)🧩 classic
Think it through
Smallest plus biggest is too big. Can the biggest number be part of the answer?
- Maybe, with some other number
- No: even with the smallest it’s too big
Show the answer
No: even with the smallest it’s too big. If it’s too big with the smallest partner, it’s too big with all of them. Drop it. Each step throws away one number for good.
And if the sum is too small?
- Drop the smallest number
- Drop the biggest number
Show the answer
Drop the smallest number. Same logic, other end: the smallest number is too small even with the biggest. Move the left finger right. Sorted order is what makes this work.
Stuck? 3 nudges, smallest first
- Look at the smallest and the biggest number together. If their sum is too big, can the biggest number ever be part of the answer?
- No! So drop it and move the right finger left. If the sum is too small, move the left finger right.
- Start with
i, j = 0, len(nums) - 1. Whilei < j: if the sum is the target, return; if it’s too small,i += 1; elsej -= 1.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def pair_sum_sorted(nums, target):take sorted numbers and a target i, j = 0, len(nums) - 1smallest number on the left, biggest on the right while i < j:until the fingers meet s = nums[i] + nums[j]add the two if s == target:exactly right? return [i, j]found the pair if s < target:too small? i += 1try a bigger left number else:too big j -= 1try a smaller right numberWhere it’s used for real
Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.