Min Stack Problem
Description
LeetCode Problem 155.
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 the element val onto the stack.
- void pop() removes the element on the top of the stack.
- int top() gets the top element of the stack.
- int getMin() retrieves the minimum element in the stack.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
- -2^31 <= val <= 2^31 - 1
- Methods pop, top and getMin operations will always be called on non-empty stacks.
- At most 3 * 10^4 calls will be made to push, pop, top, and getMin.
Solution
Approach: Store the Minimum Next to Every Value
Keeping a single min variable is not enough: after popping the current minimum, we would have to scan the whole stack to find the next one. The fix is to remember, for every level of the stack, the minimum of everything at or below that level.
Keep two stacks that always have the same height:
values: the stack itself.mins: entryiis the minimum ofvalues[0..i].
The operations are then all O(1):
push(val): pushvalontovalues, and pushmin(val, current minimum)ontomins(justvalif the stack is empty).pop(): pop both stacks. What is left on top ofminsis the minimum of the remaining values, because it was computed before the popped value arrived.top(): the top ofvalues.getMin(): the top ofmins.
For the example, pushing -2, 0, -3 gives mins = [-2, -2, -3]. getMin() returns -3; after pop(), mins = [-2, -2], so top() is 0 and getMin() is -2.
Because every level stores its own minimum, duplicate minimums need no special handling: pushing 1 twice and popping once still leaves 1 as the minimum.
Complexity: O(1) time for every operation and O(n) space, where n is the number of values on the stack.
class MinStack:
def __init__(self):
self.values = [] # the stack itself
self.mins = [] # mins[i] is the minimum of values[0..i]
def push(self, val: int) -> None:
self.values.append(val)
if self.mins:
self.mins.append(min(val, self.mins[-1]))
else:
self.mins.append(val)
def pop(self) -> None:
self.values.pop()
self.mins.pop() # the minimum below the popped value is now on top
def top(self) -> int:
return self.values[-1]
def getMin(self) -> int:
return self.mins[-1]
Now write it from memory
Close the write-up and solve it yourself against the tests.