Why Two Pointers Work
Monotonicity, the sorted-matrix picture and proofs that no pair is missed.
Why is it safe to throw away the moment a sum is too big? Draw every pair sum in a grid and the reason becomes a picture: the grid is sorted along its rows and columns, and the two pointers walk a staircase through it without stepping over any cell that could hold the answer. The same picture explains sliding windows, yields a matching lower bound, and leads to an open problem from 1976.
What you’ll learn
- Model pair problems as search in a matrix sorted by rows and columns, and prove saddleback search correct with at most probes.
- Prove by an adversary argument that an sorted matrix needs probes, and that pair sum on a sorted array needs reads.
- State exactly when a window or two-pointer scan is correct, through hereditary and upward-closed interval predicates, and refute it when monotonicity fails.
- Bound two-pointer loops with a potential function, and relate them to monotone matrix searching, SMAWK and the open problem of sorting .
The matrix of all pair sums
Take sorted arrays and and lay out every pair sum in a grid, . Moving down a column increases ; moving right along a row increases . So is a sorted matrix: non-decreasing along every row and every column. (Pair sum on one array is the special case , restricted to cells with : the widget's triangle.)
Searching for a value starting from the top-right corner is the pair-sum walk in disguise. If , every entry below it in column is at least as large, so the whole column goes: moves left. If , every entry left of it in row is at most as large, so the whole row goes: moves down. Gries called this saddleback search in The Science of Programming (1981).
def saddleback(M, x):
"""Is x in M? Every row and every column of M is sorted in non-decreasing order."""
i, j = 0, len(M[0]) - 1 # start at the top-right corner
while i < len(M) and j >= 0:
if M[i][j] == x:
return True
if M[i][j] > x:
j -= 1 # column j: from row i down, every entry is larger
else:
i += 1 # row i: left of column j, every entry is smaller
return FalseInvariant. If occurs in , it occurs in the submatrix of rows and columns . Initially that is all of .
A column goes. If , then for every row the column order gives , so column of the submatrix cannot hold .
A row goes. If , then for every column the row order gives , so row cannot hold .
Cost. Every probe that misses deletes a row or a column, and the walk leaves the matrix after row deletions or column deletions. At most misses happen before the last probe:
A matching lower bound
Let . Off the anti-diagonal the adversary fixes ; each anti-diagonal entry will be either or :
Every such matrix is sorted: an anti-diagonal entry's left and upper neighbors equal , and its right and lower neighbors equal . Off the anti-diagonal every entry is an even number other than .
The adversary answers to every probe of an anti-diagonal entry. If the algorithm halts with some anti-diagonal entry unprobed, the matrix with all of them equal to (answer: absent) and the one where that single entry equals (answer: present) agree on every probe made. Whatever it answers is wrong for one of them.
The same trick bounds pair sum itself. Let with every and target . Any such array is sorted, and a pair with misses by at least , so only the mirror pairs can hit it, each exactly when . An algorithm that reads neither element of some mirror pair cannot know whether that pair hits. So deciding pair sum on a sorted array requires reading at least elements, and the two pointers' steps are optimal up to a factor of 2.
Rectangles are different. With rows and columns, saddleback's probes are wasteful: binary search in each row costs . The optimal cost for is comparisons, achieved by binary searching the middle row and recursing on the two sub-rectangles that can still contain ; Bird (2010) tells the story as a lesson in algorithm design.
A matrix sorted by rows and columns has rows and columns. Which search makes fewer probes in the worst case?
- Saddleback search, because it is optimal
- Binary search in each row: about 200 probes, against up to about for saddleback
- They are within a constant factor of each other
- Neither beats a full scan of all entries
Show the answer
B. Binary search in each row: about 200 probes, against up to about for saddleback
Saddleback may need probes; ten binary searches need . The optimal is about here, up to constants. Saddleback is optimal only when and are comparable.
When is a window or two-pointer scan correct?
(1) If is valid, so is its sub-window . Hence every valid start for is a valid start for :
(2) If is valid and , then is valid too, so the valid starts for form one block ending at .
(3) When arrives, by (1). By (2), is invalid exactly while , so the loop stops at . moves times and at most times, never backward.
Upward closed is the mirror image: the largest valid start is non-decreasing, and the shortest valid window ending at is , found by shrinking while stays valid.
| Validity of a window | Monotone? | What it gives |
|---|---|---|
| At most distinct values; no repeated value | hereditary | longest window; counting windows |
| Sum with all values ; | hereditary | longest window (the spread needs two monotonic deques) |
| Sum with all values ; contains every required letter | upward closed | shortest window |
| Sum with negative values allowed | neither | prefix sums with a monotonic deque or a sorted structure |
| Sum exactly ; sum is even | neither | prefix sums with a hash map |
Think first Run the same loop, "longest window with sum ", on . What does it return, and which part of the proof fails?
At the window is invalid, so moves past index 0 for good. The loop then finds and and returns 2. But has sum : the answer is 3. The predicate is not hereditary: (sum ) is valid while its sub-window is not, so (1) fails, , and the start that was discarded comes back to life.
For which validity rule is the longest-window scan correct on every input?
- The window's sum is at most , where values may be negative
- The window's product is at most , where values may be zero or negative
- The window holds at most distinct values
- The window's sum is even
Show the answer
C. The window holds at most distinct values
Removing elements from a window can only lower its number of distinct values, so the rule is hereditary and the window theorem applies. Each of the other rules has a valid window with an invalid sub-window.
Potentials, monotone matrices and X + Y
The cost argument is always the same amortized one. Take the potential : it starts at most , never goes negative, and every iteration that does not end the loop lowers it by at least 1. So any loop whose pointers only move forward runs at most times, however long a single shrinking phase is. The pointer moves are free in total; what remains is the cost of updating the window's state, per move with counters in an array, or expected with a hash map.
The staircase also generalizes. For a matrix with rows and columns, let be the column of the leftmost minimum of row . is monotone if ; then finding of the middle row and recursing on the two corners gets every row minimum with evaluations. is totally monotone if every submatrix is monotone; then the SMAWK algorithm (Aggarwal, Klawe, Moran, Shor & Wilber, 1987) needs only . A window problem is the 0/1 case, valid or invalid, whose boundary is a staircase two pointers trace in . Matrices with the Monge property are totally monotone, which is where the dynamic-programming speedups of Knuth's Optimization & Monge Arrays come from.
def count_at_most(a, b, t):
"""Number of pairs (i, j) with a[i] + b[j] <= t; a and b sorted. O(len(a) + len(b))."""
j, count = len(b) - 1, 0
for x in a: # rows, top to bottom
while j >= 0 and x + b[j] > t:
j -= 1 # too big for this row, so for every later row too
count += j + 1
return count
def kth_smallest_sum(a, b, k):
"""k-th smallest of all a[i] + b[j] (k = 1 is the minimum); integers, a and b sorted."""
lo, hi = a[0] + b[0], a[-1] + b[-1]
while lo < hi: # invariant: the answer lies in [lo, hi]
mid = lo + (hi - lo) // 2
if count_at_most(a, b, mid) >= k:
hi = mid
else:
lo = mid + 1
return lo
print(kth_smallest_sum([1, 4, 7], [2, 3, 10], 5)) # sums 3 4 6 7 9 10 11 14 17 -> 9Counting the cells of that are walks the staircase between "" and "" in time; binary search on then selects the -th smallest pair sum in for integer sums spanning a range of width .
Sorting is the question this picture cannot answer. Sorting all sums takes time by sorting them outright. Fredman (1976) showed that comparisons suffice, because the sorted matrix leaves far fewer possible orders than , yet no algorithm is known that sorts in time. Selection is much easier: Frederickson and Johnson (1984) showed how to select the -th smallest entry of an sorted matrix in time.
Key takeaways
- Pair problems on sorted inputs are searches in a matrix sorted by rows and columns; the two pointers are saddleback search, deleting a whole row or column with each probe, at most probes in all.
- An adversary on the anti-diagonal shows that probes are necessary for an matrix, and pair sum on a sorted array needs reads; for rows, binary search beats the staircase, and is optimal.
- A window scan is correct exactly when validity is monotone: hereditary rules give longest windows because never decreases, upward-closed rules give shortest windows, and negative numbers break both for sums.
- Forward-only pointers bound a loop by iterations through a potential function; monotone and totally monotone matrices (SMAWK) generalize the staircase, and sorting in time remains open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Saddleback search starts at the top-right corner of a matrix sorted by rows and columns and finds . What can it discard, and why?
- Column , because entries below are smaller
- Row , because every entry left of in that row is at most
- Both row and column
- Nothing yet: it must compare with first
Show the answer
B. Row , because every entry left of in that row is at most
Row is sorted, so its entries in columns are at most , which is already too small; its entries right of were discarded earlier. Column must stay: entries below may still equal .
Why must any algorithm probe every anti-diagonal entry of an sorted matrix in the worst case?
- The anti-diagonal holds the largest entries of the matrix
- Saddleback search happens to visit those entries
- The adversary can set each of them to or not independently while keeping the matrix sorted, and only they can equal
- Sorted rows force any search to visit one entry per row
Show the answer
C. The adversary can set each of them to or not independently while keeping the matrix sorted, and only they can equal
No two anti-diagonal entries lie in the same row or column, so the sorted order imposes nothing between them; each sits between neighbors and . An unprobed one could be or , and the two answers differ.
The longest-window loop for "sum " gives a wrong answer on an array with negative numbers. What exactly breaks?
- The loop no longer terminates
- The rule is no longer hereditary: a valid window can contain an invalid sub-window, so a start that has passed may become valid again
- has to move backward, which the code forbids
- The running sum overflows
Show the answer
B. The rule is no longer hereditary: a valid window can contain an invalid sub-window, so a start that has passed may become valid again
The proof needs to be non-decreasing, which follows from heredity. With negatives, is valid for while is not, so the start discarded at becomes valid at , and the loop never returns to it.
What is known about sorting all sums of two sets of reals?
- comparisons suffice, but no algorithm is known that runs in time
- comparisons are necessary, so sorting the sums outright is optimal
- Merging the sorted rows with two pointers sorts them in time
- It is NP-hard
Show the answer
A. comparisons suffice, but no algorithm is known that runs in time
Fredman (1976) bounded the number of comparisons by , but the work of deciding which comparisons to make is not bounded that way. Turning this into an -time algorithm is a long-standing open problem.
Further reading
- D. Gries, The Science of Programming (Springer, 1981).
- R. Bird, Pearls of Functional Algorithm Design (Cambridge University Press, 2010): "Improving on saddleback search".
- M. L. Fredman, "How good is the information theory bound in sorting?," Theoretical Computer Science 1(4) (1976), 355–361.
- A. Aggarwal, M. M. Klawe, S. Moran, P. Shor & R. Wilber, "Geometric applications of a matrix-searching algorithm," Algorithmica 2 (1987), 195–208.
- G. N. Frederickson & D. B. Johnson, "Generalized selection and ranking: sorted matrices," SIAM Journal on Computing 13(1) (1984).