LeetCode 155: Min Stack — Step-by-Step Visual Trace


Medium — Stack | Design | Data Structure

The Problem

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. All operations must be performed in O(1) time complexity.

Approach

Use two stacks - one main stack for all elements and an auxiliary min_stack to track minimum values. Push to min_stack only when the new value is less than or equal to the current minimum, and pop from min_stack only when removing the current minimum.

Time: O(1) · Space: O(n)

Code

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)

    def pop(self) -> None:
        if self.stack:
            if self.stack[-1] == self.min_stack[-1]:
                self.min_stack.pop()
            self.stack.pop()

    def top(self) -> int:
        if self.stack:
            return self.stack[-1]

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

Watch It Run

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.


Comments