Proofs: Stack with minimum
These are the human proofs of Stack with minimum, at full length.
The stack with minimum returns the least item after each operation full
This proof shows: correctness.
Setting. The structure is a stack of pairs. Write its state, from the bottom to the top, as with . The stack that the user sees is . The items come from a set with a total order.
Invariant (M). for each .
We show that each operation keeps (M), that the stack of the changes as a stack must, and that each query returns the right value. The underlying stack of pairs meets the stack laws, so a push of a pair adds it at the top and a pop removes and returns the top pair.
Initialization. The new structure is empty, , and (M) holds with no index to check.
PUSH. Line L1 sets if , and otherwise. Line L2 pushes , so the new state has and , and the pairs below are unchanged. For , (M) holds as before. For : if then . If then, by (M) for ,
The user's stack is .
POP, . Line L3 removes the top pair , and line L4 returns , the top item of the user's stack. The pairs are unchanged, so (M) holds for them, and the user's stack is .
TOP, . Line L5 returns . Nothing changes.
MIN, . Line L6 returns , which by (M) is , the least item of the user's stack. Nothing changes.
The lean variant. The variant keeps the items in a stack and a second stack that receives on a push exactly when is empty or , and loses its top on a pop exactly when the popped item equals . Its invariant is: is the sequence of the prefix minima with repeats, that is, of the items with for all , in the order of . A push of appends to this sequence exactly when , which is the test. On a pop of , the item is in the sequence exactly when every earlier item. In that case it is the last entry of and equals . If it is not in the sequence, then some earlier item is less than , so and the test fails. So the test removes from exactly when it is there, and is kept, because the last prefix minimum is the minimum. With the strict test on push, a repeated minimum is not recorded, and the first pop of it removes the only copy from ; this is the pitfall of the page.