Proofs: Queue with minimum
These are the human proofs of Queue with minimum, at full length.
The two-stack queue with minimum is a FIFO queue and returns its least item full
This proof shows: correctness, amortized.
Setting. The structure has two stacks with minimum, and . We use only their laws: PUSH adds an item at the top, POP removes and returns the top item, and MIN returns the least item of a non-empty stack. Write and , each from the bottom to the top.
Invariant (Q). The queue, from the front to the back, is
So the front is the top of when is not empty, and the back is the top of .
At the start both stacks are empty and the queue is empty, so (Q) holds.
ENQUEUE. Line L1 pushes on , so . By (Q) the queue becomes , which is the old queue with at the back.
DEQUEUE, the queue not empty.
Case . Line L2 skips the transfer. Line L5 pops from and returns it. By (Q) is the front item, and the rest is the old queue without its front.
Case . Then , because the queue is not empty. The loop of lines L3 and L4 keeps this loop invariant at its test: for some , and from the bottom to the top. It holds for . One iteration pops from and pushes it on , which gives the invariant for . The value grows by exactly 1 in each iteration, and the loop stops when is empty, at . Then with at the top, and is empty. In the notation of (Q), and , so the queue read by (Q) is , which is unchanged. Line L5 then pops , the front item, as in the first case.
MIN, the queue not empty. The set of items of the queue is the union of the items of and of , by (Q). If is empty, line L6 returns the least item of , which is the least item of the queue. If is empty, line L7 returns the least item of . Otherwise line L8 returns the smaller of the two minima, which is the least item of the union. Nothing changes.
Amortized cost. Count one unit for each PUSH and each POP on or ; each costs on a stack with minimum. Let , twice the size of . Then and at the start.
- ENQUEUE costs 1 and raises by 2: amortized cost 3.
- DEQUEUE without a transfer costs 1 and does not change : amortized cost 1.
- DEQUEUE with a transfer of items costs , and drops from to 0: amortized cost 1.
- MIN costs at most two MIN calls on stacks, and does not change : amortized cost .
The sum of the potential differences telescopes, so for any sequence of operations from the start, the total cost is at most the sum of the amortized costs minus the final potential, which is at most stack operations.