Proofs: Monotonic deque over prefix sums
These are the human proofs of Monotonic deque over prefix sums, at full length.
The monotonic deque over prefix sums finds a shortest subarray with sum at least K full
This proof shows: correctness.
We use the pseudocode of the page on and , with and . A pair with is valid if , which says that has sum at least . Let be the smallest over valid pairs, or if there is none.
Lemma 1 (order). After line L7 of each step, the indices in increase from front to back, and so do their prefix sums, strictly.
Proof. By induction on the steps. Pops keep the property. Line L7 pushes , which is larger than every index in . After line L6 either is empty or , so the prefix sums still strictly increase.
Lemma 2 (soundness). Every pair recorded in line L5 is valid.
Proof. Line L5 runs only when the test of line L4 holds, that is for the popped front . The index was pushed at an earlier step, so .
So at the end, with if no pair is ever recorded.
Lemma 3 (completeness). If , some pair of length is recorded.
Proof. Choose a valid pair with . The index is pushed in step . We show that it is still in when step starts.
Suppose it is popped at the front in a step with . Then is valid by Lemma 2 and , a contradiction.
Suppose it is popped at the back in a step with . Then , so , and is valid with , a contradiction.
So is in at the start of step . By Lemma 1, every index in front of has , so it passes the test of line L4. Hence the loop of lines L4 and L5 pops all of them, then reaches , which passes the test, and pops it with the pair . At that point , so becomes unless it is already .
Theorem. SHORTEST-AT-LEAST returns , and if it returns a valid pair of length .
Proof. By Lemma 2, every value given to is the length of a valid pair, so always, and is valid whenever it is set. By Lemma 3, at the end. The algorithm stops because each index is pushed once and popped at most once, so the loops of lines L4 and L6 run at most times each in total.