Proofs: Sliding window maximum with monotonic deque
These are the human proofs of Sliding window maximum with monotonic deque, at full length.
The monotonic deque reports the maximum of every window of length k full
This proof shows: correctness, termination, complexity.
We use the pseudocode of the page, with . For let . An index is a leader of if for every with . Let be the list of the leaders of in increasing order of index.
Lemma 1. The values of strictly decrease, is the last element of , and the first element of is an index with .
Proof. If are both leaders, then because . The index is a leader, because there is no with . Let be the largest index in with . Each with has , by the choice of , so is a leader. A leader would need , which is not possible. So is the first leader.
Lemma 2. For , the leaders of are: the leaders of with and , and the index .
Proof. Take with . Then and . The condition " for all " is the condition for together with .
Claim. After line L5 of step , equals from front to back. So line L6 appends for each , and the output is for .
Proof. By induction on .
Step . is empty after line L1. Line L3 does nothing, line L4 gives , and line L5 tests , which is false. .
Step . By induction, before line L3. Its values strictly decrease by Lemma 1. Line L3 pops from the back while the back value is at most . Because the values decrease from front to back, the popped indices are exactly the indices of with value at most , and the kept ones are those with value greater than . Line L4 appends . Now holds the leaders of with , then . All indices of are at least , since they are in . The only one that can be less than is itself, and if it is in , it is at the front because the indices increase. Line L5 removes it exactly in this case. ( is never equal to , so line L5 never removes the index just pushed.) By Lemma 2, .
Output. By Lemma 1 the front of has the maximum value of . For , is the window that starts at . So line L6 appends , for in order.
Why the popped indices lose nothing. An index popped by line L3 at step has and . Each window with that contains also contains , because windows are intervals. So is never the strict maximum of a later window, and if it ties the maximum, has the same value. The proof above makes this exact through Lemma 2.
Termination and cost. The for loop runs times. Each index enters once, in line L4, and leaves at most once, so the total number of pops in lines L3 and L5 is at most , and the while loop of line L3 runs at most times with a pop in total. Each step ends the while loop with at most one comparison that is false. So the total number of comparisons of values in line L3 is at most : there are at most pops at the back, since the index is never popped at the back, and at most false tests, since step 0 makes none. The time is . At each moment , so .