Two Sum II
Find the pair in a sorted array that adds up to a target
DSA, Medium, Two Pointers
Which structure or algorithm, and what does it cost.
A list nums is sorted from smallest to largest, and equal values may repeat. You also get an integer target. Return the positions [i, j], with i < j, of two elements whose values add up to target. Positions start at 0. Each input has at most one valid pair. Return [] if there is none.
Examples
Constraints
- 0 <= length of
nums<= 100,000. - Each value is between -1,000,000,000 and 1,000,000,000.
numsis in non-decreasing order.
Your answer must contain
- The simple method and its cost; the better method; code; time and memory cost; and a hand trace of example 1 through your code.
Target Aim for O(n) time and O(1) extra memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
The list is sorted. What can the order rule out without testing every pair?
Hint 2 the approach
If the sum is too small, the smallest value cannot be in any pair. If it is too big, the largest value cannot. Decide which end to drop.
Hint 3 the key step
Put a marker at each end. If the sum is too small, move the left marker up. If too big, move the right marker down. Stop when they meet.
Walkthrough
Full walkthrough brute force to best
Brute force
Try each pair of positions in turn and stop at the first pair whose values reach the target. This always works. It takes O(n^2) time and O(1) memory. With 100,000 values that is about 5 billion pair tests, which is too slow.
Better method
Keep a table from each value to its position and look up target minus the current value, as in Two Sum. This takes O(n) time but O(n) memory, and it ignores the sorted order.
For each position, binary search the part of the list after it for the partner value. This uses the order and keeps memory at O(1), but it takes O(n log n) time.
Best method
Use the order with two markers, one at each end. Add the two values they point at. If the sum equals the target, return the two positions. If the sum is too small, move the left marker right. If it is too big, move the right marker left. Stop when the markers meet. This is correct because of one fact: if a pair exists, both of its positions stay between the markers. Say the left value is too small for the current right value. The right value is the largest one still in range, so the left value cannot reach the target with any partner, and you can drop it for good. The same holds for the right value when the sum is too big. Each step drops one position, so the walk is linear.
Hand trace
Run on nums = [2, 4, 9, 14, 20] with target 23. The markers start at 0 and 4: 2 + 20 = 22, which is too small, so the left marker moves to 1. Then 4 + 20 = 24 is too big, so the right marker moves to 3. Then 4 + 14 = 18 is too small, so the left marker moves to 2. Then 9 + 14 = 23, so the answer is [2, 3].
Code
def pair_in_sorted(nums, target):
lo, hi = 0, len(nums) - 1
while lo < hi:
s = nums[lo] + nums[hi]
if s == target:
return [lo, hi]
if s < target:
lo += 1
else:
hi -= 1
return []Time and memory
O(n) time, because each step moves one marker and together they move at most n steps. O(1) extra memory, because only the two marker positions and their sum are kept.
Common mistakes
- Moving both markers on every step. When the sum is too small, only the left marker may move, or the answer can be skipped.
- Looping while the left marker is not past the right one. The markers can then meet on one position and return it twice, such as [0, 0].
- Dropping a value because it already appeared. Equal values at different positions can form a pair, so [3, 3, 8] with target 6 must give [0, 1].