min-stack.py
stack/min-stack.py · Python · 677 B · 2026-02-17 21:05
# Use a second stack to keep track of minimum so far. Pop and push every time to the minstack too. # stack # Min stack: O(1) time, O(n) space class MinStack: def __init__(self): self.stack = [] self.minstack = [] def push(self, val: int): self.stack.append(val) if not self.minstack: self.minstack.append(val) else: mini = min(self.minstack[-1], val) self.minstack.append(mini) def pop(self) -> None: self.stack.pop() self.minstack.pop() def top(self) -> int: return self.stack[-1] def get_min(self) -> int: return self.minstack[-1]