3/32
Part 1 of 6 · Two pointersLearn and do

Each step rules out a whole row or column of pairs

Why is it safe to throw a value away after one comparison? Write every pair's sum in a grid:

Every pair's sum
sums
2503004507008001200100350400550800900130025055070095010501450300750100011001500450115012501650700150019008002000

Each cell adds its row's size and its column's size. The target, 1150, is 450 + 700.

The list is sorted, so the sums grow to the right along a row and down a column.

Step 1 looked at the top right corner, 100 + 1200 = 1300. That's too big. Every other cell in the 1200 column sits lower down, so it's at least 1300 too. The whole column is out, and hi -= 1 loses nothing.

Step 2 looked at 100 + 800 = 900. That's too small, and 800 is the biggest partner 100 has left. Every other cell left in the 100 row sits to its left, so it's smaller still. The whole row is out.

Every step works the same way:

The step that ruled out each pair, and * for the pair it found
step
2503004507008001200100222221250333313004441450*51700518001

Step 1 rules out the whole 1200 column, step 2 the 100 row, and so on.

Each step rules out a whole row or a whole column by moving one pointer one place. The pointers start n - 1 places apart, so the loop takes at most n - 1 steps.

Write moves on the same sizes. It runs the pointers the way pair_with_sum does and lists which one each step moved, so you can count the steps.