Sometimes a data structure needs to answer a question fast that a plain stack cannot: "what is the smallest element currently inside?" Scanning the whole stack costs O(n) each time. With a little extra bookkeeping per element, the answer can be kept ready at all times.
In a card game, numbered cards (negative numbers included) are dealt onto one face-up pile, and at any moment a player may ask for the lowest number anywhere in the pile. Write a class MinStack for the pile with these methods:
push(x)– place cardxon top of the pile.pop()– take the top card away and return nothing (unlikelist.pop, it does not hand back the removed value).top()– return the top card.get_min()– return the lowest card currently in the pile.
Every method must run in O(1) time. pop, top and get_min are only called on a non-empty stack. The tests drive the class with run_ops and compare the list of return values (None for methods that return nothing).
Examples
Input: ops = ["MinStack", "push", "push", "push", "get_min", "pop", "top", "get_min"]
args = [[], [4], [6], [1], [], [], [], []]
Output: [None, None, None, None, 1, None, 6, 4]
Explanation: the lowest card is 1 until it is taken away; after that the lowest is 4 again.
Constraints
- At most 100 operations per test
-10**4 <= x <= 10**4
Goals
- Design a class whose methods share state through self
- Keep auxiliary data alongside a stack so that a query answers in O(1)
- Reason about why recomputing min(stack) on every call is too slow