Design a stack class that supports the push
, pop
, top
, and getMin
operations.
MinStack()
initializes the stack object.void push(int val)
pushes the elementval
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.
Each function should run in O(1) time.
Example 1:
Input: ["MinStack", "push", 1, "push", 2, "push", 0, "getMin", "pop", "top", "getMin"]
Output: [null, null, null, null, 0, null, 2, 1]
Explanation:
MinStack minStack = new MinStack();
minStack.push(1);
minStack.push(2);
minStack.push(0);
minStack.getMin(); // return 0
minStack.pop();
minStack.top(); // return 2
minStack.getMin(); // return 1
- Use two parallel stacks - one for actual values and one for tracking minimums.
- When pushing, add value to main stack and add min(new_value, current_min) to min stack.
- When popping, remove from both stacks together, ensuring min stack always reflects minimum of remaining elements.
In [5]:
class MinStack:
def __init__(self):
self.stack=[]
self.minstack=[]
def push(self,val):
self.stack.append(val)
#min of val or top of minstack(if stack is not empty)
val=min(val, self.minstack[-1] if self.minstack else val)
self.minstack.append(val)
def pop(self):
self.stack.pop()
self.minstack.pop()
def top(self):
return self.stack[-1]
def getmin(self):
return self.minstack[-1]