Proofs: Two pointers with distinct counts
These are the human proofs of Two pointers with distinct counts, at full length.
Two pointers with distinct counts finds the longest window with at most k values full
This proof shows: correctness.
We use the pseudocode of the page on and . For let be the number of distinct values in , with . Call valid if . For let be the smallest such that is valid. It exists because is valid.
Lemma 1 (monotone). If then . So a subarray of a valid subarray is valid, and for .
Proof. The values of are among those of . If then is not valid, so neither is , which contains it. Hence .
Invariant. At the start of the step for (line L2), , the table maps each value of to its positive count and holds no other key, and . After line L7 of the same step, the same holds with in place of .
Proof. For , line L1 gives , an empty table, and .
Assume the invariant at the start of the step for . Lines L3 and L4 add one to the count of , and add a key and one to exactly when is not in . So the table and are correct for the window . Now by Lemma 1.
Each run of lines L6 and L7 takes out of the window: it lowers its count, deletes the key and lowers when the count reaches zero, which is when is not in . So the table and stay correct for the window with the new . The loop runs while , that is while the window is not valid. If the window is not valid by the definition of , so the loop continues. At the window is valid and the loop stops. Since the loop starts with , it stops with .
Theorem. DISTINCT-WINDOW returns and a start with .
Proof. For a fixed end , the valid subarrays are those with , by Lemma 1, and the longest of them has length . By the invariant, line L8 tests exactly this length, , for every . The end gives only the empty subarray, with length , which is the starting value of in line L1. So after the loop, is the maximum over all ends, and is the start of a window of that length that was valid when it was recorded. Each step moves once, and moves at most times in total because , so the algorithm stops.