At a supermarket checkout, shoppers join at the back and are served from the front. The manager also wants to know, at any moment, the smallest basket (number of items) still waiting, in constant time. Write the class MinQueue for integer basket sizes, built from two stacks (Python lists used only with append and pop), not from a deque and not by scanning a list:
MinQueue(): open an empty line.push(x): a shopper withxitems joins at the back.pop(): serve the shopper at the front and return their item count.front(): return the front shopper's item count without serving them.min_val(): return the smallest item count still in the line.
pop, front and min_val are only called while someone is in the line.
Examples
Input: ops = ["MinQueue", "push", "push", "push", "min_val", "pop", "min_val", "pop", "min_val", "front"]
args = [[], [3], [1], [2], [], [], [], [], [], []]
Output: [None, None, None, None, 1, 3, 1, 1, 2, 2]
Constraints
- At most
2 * 10**4operations - Target: amortised
O(1)per operation
Goals
- Build a queue from two stacks
- Augment each stack with running minimums so min is O(1)
- Understand why the transfer step is amortised O(1)