Example 1
- Input
- ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]]
- Output
- [null,null,null,null,-3,null,0,-2]
Push -2, 0, -3. getMin returns -3. After pop, top returns 0 and getMin returns -2.
Design a stack that supports push, pop, top and getMin, with every operation running in constant time. Storing the running minimum alongside each entry makes the minimum query a plain top-of-stack read.
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class: MinStack() initializes the stack object, void push(int val) pushes val onto the stack, void pop() removes the top element, int top() returns the top element, and int getMin() retrieves the minimum element in the stack. Every method must run in time.
The constructor and push/pop produce null in the operation-sequence output. top and getMin return integers. Empty-stack queries and pops are outside the valid input contract.
-2^31 <= val <= 2^31 - 1pop, top and getMin are always called on non-empty stacks.3 * 10^4 calls are made to push, pop, top and getMin.Push -2, 0, -3. getMin returns -3. After pop, top returns 0 and getMin returns -2.
Push 1, 2. The minimum of the stack is 1.
A one-element stack has the same top and minimum. After removing its only entry, pushing the smallest signed 32-bit value starts a fresh stack; no stale minimum survives.
The minimum occurs twice. Popping 0 leaves both copies; popping the newer -2 still leaves the older -2. A single minimum flag without multiplicity or history would lose this information.
A stack remembers values in last-in-first-out order, but its smallest value may be buried below the top. In Example 1, pushing -3 changes the minimum from -2 to -3; popping -3 must restore -2. Store a snapshot of the minimum with each entry, so removing the newest entry exposes the correct older snapshot. Duplicate minima need their own snapshots too.
Reveal Rescan For Minimum: intuition, complexity, and code
[-2, 0, -2]: popping one copy must leave the other minimum intact.-2147483648 and 2147483647 work using comparisons; arithmetic encodings based on 2 * val - min can overflow a Java int.When a last-in-first-out structure must answer a running property in constant time, store that property alongside each entry so push and pop maintain it for free.