PracticeNeetCode ↗LeetCode ↗
Design a stack that supports push, pop, top, and retrieving the minimum element — all in O(1) time.
getMin() in O(1), since the minimum could be buried anywhere below the top.min(new value, current min) onto the min-stack — its top is then always the current minimum.stack for the real values, min_stack for running minimums.push(val): push val onto stack; push min(val, min_stack top) (or just val if min_stack is empty) onto min_stack.pop(): pop both stacks together, so they stay the same size.getMin() reads min_stack's top; top() reads stack's top — both O(1).Time: O(1) for every operation — Space: O(n)
class MinStack:
def __init__(self) -> None:
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
current_min = min(val, self.min_stack[-1]) if self.min_stack else val
self.min_stack.append(current_min)
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]How the solution above works, piece by piece.
stack holds the values, min_stack holds "the minimum so far" at each height.push: append the value, and append min(val, previous minimum) to min_stack (or just val if it's the first element).pop removes from both stacks, so the minimum automatically goes back to what it was before that push.top reads stack[-1]; getMin reads min_stack[-1]. No searching needed.Running the example operations: