1def pair_sum(a, target):2 i, j = 0, len(a) - 13 while i < j:4 s = a[i] + a[j]5 if s == target:6 return i, j7 if s < target:8 i += 19 else:10 j -= 111 return Nonea[0]1a[1]3a[2]4a[3]6a[4]8a[5]11starget10checksij
Cells: the sorted list a, one value per slotPucks i and j: the two pointers (indexes)A faded cell: a value ruled out for goodpair_sum walks two indexes inward over the sorted list 1, 3, 4, 6, 8, 11 to find two values that add up to 10. Too big: the right value can pair with nothing, so j steps left. Too small: the left value can pair with nothing, so i steps right. Each check drops one value, so the answer (2, 3) takes 5 checks, never more than n − 1.

The problem

  1. A sorted list: 1, 3, 4, 6, 8, 11. Find two numbers that add up to 10. Brute force tries every pair: 6 numbers make 15 pairs, and the count grows like n². Sorted order lets us do much better.

Walking inward

Why it works

What happens

;; step 1/9 · problem
a = [1, 3, 4, 6, 8, 11]   (sorted, n = 6)
target = 10

brute force: try every pair a[p] + a[q], p < q
  pairs = n(n - 1)/2 = 6·5/2 = 15
  here it looks at 10 pairs before it finds (2, 3)
  n = 1000 → 499500 pairs: O(n²)

Two pointers needs sorted input. On an unsorted list, sort first (sorted(a) in Python returns a new sorted list); merge sort takes O(n log n) time (MIT 6.006, Lecture 3), so the whole method is O(n log n), still far less than the O(n²) of checking every pair. The function returns indexes, not values: (2, 3) means a[2] = 4 and a[3] = 6. If no pair exists, the pointers meet and it returns None.