Proofs: Two-pointer pair search
These are the human proofs of Two-pointer pair search, at full length.
Two-pointer pair search finds a pair with sum t if and only if one exists full
This proof shows: correctness, termination.
We use the pseudocode of the page. The array is sorted, . A solution is a pair of indices with and . Write for the set of solutions with .
Claim. PAIR-SEARCH stops after at most iterations of the loop of line L2. It returns a solution if a solution exists, and NIL otherwise.
Proof. We use this invariant, checked each time the test of line L2 is about to run:
(P) , , , and if then .
Initialization. Line L1 sets and . Then because , and , so the last part holds.
Maintenance. Assume (P) and . Line L3 sets ; both indices are in by (P). If , line L4 returns , which is a solution because . Otherwise there are two cases.
- Case (line L5). Take any with . Because is sorted and , , so . So no solution in has first index , and . Line L5 sets to , so the last part of (P) still holds. The bounds hold because the new is at most .
- Case (line L6). Take any with . Because , , so . So no solution in has second index , and . Line L6 sets to , and (P) holds as before; the new is at least .
In both cases no solution of the old range is lost: this is the statement that a pointer move never skips an answer.
Termination. Let . Each iteration that does not return runs exactly one of lines L5 and L6, and each of them decreases by exactly 1. At the start , and the loop runs only while . So there are at most iterations when , and none when .
Result. If line L4 returns, the result is a solution, as shown. Otherwise the loop stops with , so or by (P). Then no pair with exists, and . By the contrapositive of the last part of (P), , so NIL is the right answer.
Exact count on a no-answer input. If no solution exists, line L4 never returns, so each iteration decreases by 1 from to 0, and the loop runs exactly times for .
Remark on the order of solutions. The proof shows only that some solution stays in the range. A specific solution can leave the range: on with , the algorithm returns and never looks at the solution . To list all solutions, use the variant of the page that skips the blocks of equal items after a match.