Skip to the solution
MediumDSA4 min read

How do you design a min stack with O(1) getMin?

291 views

The problem

Question presented to candidate: "Design a stack class in Python that supports push, pop, top and get_min, where every one of those operations runs in O(1) time. Talk me through how you keep the minimum correct after a pop."

What a strong answer should cover:

  • Why a single current-minimum variable fails after popping the minimum.
  • Storing (value, minimum so far) on each entry, or an auxiliary mins stack that is pushed on <=.
  • All four operations O(1); O(n) extra space, and when the two-stack version saves memory.
  • The duplicate-minimum case, and why < instead of <= breaks it.
  • Python specifics: a list of tuples as the stack; min(self.stack) would be O(n); stack[-1] on an empty list raises IndexError; Python ints never overflow, so the encoded-difference trick is safe here.

Clarifying questions expected:

  • "What should top or get_min do on an empty stack?"
  • "Can values repeat?"

Code / implementation expected: Yes โ€” a Python class backed by a list of (value, min) tuples.

  • dsa
  • stack
  • design

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMin stack of (value, min) pairs, including duplicate minimums
PythonTwo-stack version: the < versus <= bug, and memory use

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 104 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Merge k sorted lists: heap vs divide-and-conquer โ€” which is better for n=10k?

Continue