The list is sorted, so start one pointer at each end. If the pair adds up too small, move the left one right; too big, move the right one left. Each step rules out a whole row of pairs: O(n) time, O(1) space.
▼The problem
LeetCode 167 (Medium). Given a 1-indexed array numbers sorted in non-decreasing order and a target, return the positions [index1, index2] (1-indexed, index1 < index2) of the two numbers that add up to target. Exactly one solution exists, the same element can't be used twice, and only O(1) extra space is allowed.
Examples (LeetCode's): [2,7,11,15], 9 → [1,2]; [2,3,4], 6 → [1,3] (both in scene 2); [-1,0], -1 → [1,2] (checked, not shown).
The solution
def twoSum(numbers, target):
l, r = 0, len(numbers) - 1
while l < r:
s = numbers[l] + numbers[r]
if s == target:
return [l + 1, r + 1]
if s < target:
l += 1
else:
r -= 1Transcript
Two Sum Two. You get sorted numbers, smallest first, and a target. Find the two that add up to the target and return their positions, counting from one. Exactly one pair works, and only constant extra space is allowed.
Take two, seven, eleven, fifteen, with target nine. Two plus seven is nine, so the answer is one, two. With two, three, four and target six, it's one, three.
The slow way tries every pair: six numbers make fifteen pairs, n numbers about n squared over two. A hash map, like in Two Sum, is fast but needs extra memory, which isn't allowed here.
Instead, use the order. Point left at the smallest number and right at the largest. If their sum is too small, the left number fails even with the biggest, so it fails with all of them: move left forward. If it's too big, the right number is too big even with the smallest: move right back. If it's equal, we're done.
Try one, three, four, six, eight, eleven, with target ten. One plus eleven is twelve: too big, so eleven goes. One plus eight is nine: too small, so one goes. Three plus eight is eleven: eight goes. Three plus six is nine: three goes. Four plus six is ten. The answer is three, four.
Why can't we skip the answer? Picture every pair in a grid. Each step crosses out a whole row or column, only pairs that can't work. The answer cell never gets crossed out, so the pointers must reach it.
In code, left starts at zero, right at the end. While left is before right, add the two. If they match, return both positions plus one. If the sum is too small, step left forward; otherwise, step right back.
Each step moves one pointer, so at most n minus one steps: linear time. A million numbers make half a trillion pairs, but at most a million steps. Two pointers: constant space.
Start at both ends, compare, move the side that's off. That's Two Sum Two.