We maintain two stacks: one for the actual values and another for the minimum values encountered so far. When pushing a value, we push the current minimum onto the second stack.
push(val): Always pushvaltostack1. Forstack2, pushmin(val, stack2[-1])ifstack2is not empty, otherwise pushval.pop(): Pop from both stacks.top(): Return the top ofstack1.getMin(): Return the top ofstack2.
- Time Complexity: O(1) for all operations.
- Space Complexity: O(N).
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
else:
self.min_stack.append(self.min_stack[-1])
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]