SDE & MLE Prep

155. Min Stack

Problem

Design a MinStack supporting push(val), pop(), top() and getMin() (the smallest value currently on the stack), each in O(1) time. pop, top and getMin are only called on a non-empty stack.

Example: push −2, push 0, push −3 → getMin() = −3; pop() → top() = 0, getMin() = −2

Store (value, min so far) pairs; the minimum is always at the top in O(1).

Complexity: O(1) per operation.

class MinStack:
    def __init__(self):
        self.st = []  # (val, current min)

    def push(self, val: int) -> None:
        self.st.append((val, min(val, self.st[-1][1]) if self.st else val))

    def pop(self) -> None:
        self.st.pop()

    def top(self) -> int:
        return self.st[-1][0]

    def getMin(self) -> int:
        return self.st[-1][1]