download

Design a stack that returns its minimum in O(1)

Algorithms~10 minReviewed 1 Nov 2026Free · No sign-in

Question

A shop's admin page keeps a stack of price edits for one product, newest on top. "Undo" pops the latest edit. The page also shows the lowest price still in the stack.

Write a class MinStack with push(price), pop() and get_min(). All three must be O(1), so get_min() can't scan the stack.

"PYTHON"
s = MinStack()
for price in (50, 30, 70, 30):
    s.push(price)
s.get_min()  # 30
s.pop()      # 30
s.get_min()  # 30, the other 30 is still there
s.pop()      # 70
s.pop()      # 30
s.get_min()  # 50
"CODE · PYTHON"
class MinStack:
    def __init__(self):
        self.items = []

    def push(self, price):
        ...

    def pop(self):
        ...

    def get_min(self):
        ...
Show hints (3)
  1. "ONE VARIABLE FAILS"

    Keep one min variable. Push 50 and 30, so it holds 30. Now pop the 30. What is the minimum now? Without scanning the stack, you can't tell.

  2. "REMEMBER THE PAST"

    When you push a price, the minimum of everything below it is already known. Could each entry remember it?

  3. "STORE A PAIR"

    Push (price, min(price, previous minimum)). Then get_min() is just the second number of the top entry, and pop() brings back the older minimum.

Show checked explanation

Store a pair on each push: the price and the lowest price at or below it. get_min() reads the pair on top. When you pop, the pair below already holds the minimum for the smaller stack. Every operation is O(1), and the stack uses O(n) extra memory.

"SOLUTION · PYTHON"
class MinStack:
    def __init__(self):
        self.items = []  # pairs: (price, lowest price at or below it)

    def push(self, price):
        low = min(price, self.items[-1][1]) if self.items else price
        self.items.append((price, low))

    def pop(self):
        return self.items.pop()[0]

    def get_min(self):
        return self.items[-1][1]


s = MinStack()
for price in (50, 30, 70, 30):
    s.push(price)
print(s.items)
print(s.get_min(), s.pop(), s.get_min(), s.pop(), s.pop(), s.get_min())
"OUTPUT"
[(50, 50), (30, 30), (70, 30), (30, 30)]
30 30 30 70 30 50

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Each entry stores two things: the price, and the lowest price from the bottom of the stack up to that entry.

pushpricelowest so farstack, bottom to top
15050(50, 50)
23030(50, 50), (30, 30)
37030..., (70, 30)
43030..., (30, 30)

get_min() reads the second number of the top entry. Pop the top 30, and the new top is (70, 30), so the minimum is still 30. Pop twice more, and the top is (50, 50).

Why is the stored minimum always right? An entry can only be reached when everything above it is gone. The entries below it never change while it is there. So the minimum it saved at push time is still the minimum when it is back on top.

Every method does one append, one pop or one index on a list, so each is O(1). For append, that is O(1) amortized, as on any list. The price is O(n) extra memory: one more number per entry.

You can save memory with a second stack that holds only the minimums:

"PYTHON"
class MinStackTwoLists:
    def __init__(self):
        self.items, self.mins = [], []

    def push(self, price):
        self.items.append(price)
        if not self.mins or price <= self.mins[-1]:
            self.mins.append(price)

    def pop(self):
        price = self.items.pop()
        if price == self.mins[-1]:
            self.mins.pop()
        return price

get_min() returns self.mins[-1]. With 50, 30, 70, 30, mins holds [50, 30, 30]. The <= matters: both 30s go into mins, so popping one still leaves the other.

Common mistakes

  • Keeping one min variable. Popping the current minimum leaves no way to find the next one without scanning the stack, which is O(n).
  • Writing price < self.mins[-1] instead of <= in the two-list version. With 50, 30, 70, 30, mins gets one 30. The first pop removes it, and get_min() says 50 while a 30 remains.
  • Writing get_min() as min(self.items). The answer is right, but the method is O(n), which the task forbids.
  • Not deciding what an empty stack does. Here pop() and get_min() raise IndexError, like list.pop(). Say so in the interview instead of returning 0, which could be a real price.

Follow-up questions

  • "Can it return the maximum too?" Yes. Store three numbers per entry: the price, the lowest and the highest at or below it. push computes both from the entry below. Every operation stays O(1).
  • "How much memory does the two-list version save?" It depends on the order. Push 10, 20, 30, 40 and mins holds only [10]. Push 40, 30, 20, 10 and every price is a new minimum, so mins holds all four. In the worst case it is still O(n).
  • "Why not keep the prices in a heap?" A heap also shows the minimum in O(1), but undo must remove the newest edit, not the smallest. In a heap that edit can sit anywhere, so finding it is O(n). The stack keeps the order undo needs, and the pairs add the minimum.

What a strong answer covers

Explains why one variable fails before coding. Stores the minimum next to each item, and handles a repeated minimum with <= in the two-list version. States O(1) time and O(n) extra memory, and decides what an empty stack does.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from Crushing the Technical Interview (Keith Henning, 2025); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.