Proofs: Sliding window for longest distinct substring
These are the human proofs of Sliding window for longest distinct substring, at full length.
The sliding window returns the leftmost longest substring without repeated characters full
This proof shows: correctness, termination.
We use the pseudocode of the page. The string is . A substring with is repeat-free if its characters are distinct. For let be the smallest such that is repeat-free; it exists since is repeat-free. Let be the largest with , or .
Lemma 1 (closed under sub-intervals). If is repeat-free and , then is repeat-free. So for each , is repeat-free if and only if .
Proof. The characters of are a subset of those of , at distinct positions. For the second part, if is repeat-free, so is each with ; and with is not repeat-free by the choice of .
Lemma 2. , and for .
Proof. For , the window is repeat-free if and only if is repeat-free and no with has . By Lemma 1 the first condition is . The second is , since is the last earlier copy of . The window is always repeat-free, and because and . So the smallest valid is .
Claim. After step of the loop of line L2:
(U) ; is the largest with , or if there is none, for every character ; ; and is the smallest such that is repeat-free and .
On return, is the length of a longest repeat-free substring of , and is the smallest start of one; for the result is .
Proof. By induction on . Before step 0, by line L1, , , and for all .
Line L3. Before line L4 of step , is the largest with , which is (for , it is ). The value of before line L3 is for , and 0 for . So line L3 sets to by Lemma 2, and to for .
Line L4. It sets , the largest with . The other entries are unchanged and stay correct.
Line L5. The longest repeat-free substring that ends at is , by Lemma 1, of length . If this is larger than , line L5 sets to it and to . The new is . A repeat-free substring of the new length that ends at must have , since all earlier ones were shorter; and the only one that ends at with this length starts at . So is the smallest start. If the length is not larger, and stay. The new best substrings that end at , if any, start at , which is larger than the old ; so stays the smallest start.
Result. Every repeat-free substring has by Lemma 1, so its length is at most after step . And is repeat-free, by (U). For the loop does not run and line L6 returns .
No skipped answer. The left end only increases, by Lemma 2 and line L3. A start that the left end has passed gives a window with a repeat, and every window with contains , so it has the same repeat by Lemma 1. So no repeat-free window with start and end at or after exists, and passing loses no candidate.
Termination and cost. The loop of line L2 runs times, and each iteration does table operations. Line L1 initializes a table of size . The total time is .