InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Min Stack

medium Original ↗ 00:00

Problem

Design a stack that, in addition to the usual operations, can report its minimum element at any time. Implement a class MinStack with:

  • push(val) — put val on top of the stack
  • pop() — remove the top element
  • top() — return the top element without removing it
  • getMin() — return the smallest element currently in the stack

Every operation, including getMin, must run in O(1) time. pop, top, and getMin are only ever called on a non-empty stack.

Examples

  • push(-2), push(0), push(-3)getMin() = -3; then pop()top() = 0, getMin() = -2. The minimum returns to its previous value when the element that set it is popped.
  • push(5), push(7)getMin() = 5; pop()getMin() = 5. Popping a non-minimum leaves the minimum unchanged.
  • push(1), push(1), pop()getMin() = 1. With duplicate minima, removing one copy must not lose the other.

Constraints

  • -2^31 <= val <= 2^31 - 1
  • Up to 3 * 10^4 operations total

The operation count is small, but the O(1)-per-operation requirement is the real constraint. A getMin that scans the stack is O(n) and does not satisfy the problem.

Think about it first

Hint 1 A single "current minimum" variable breaks the moment you pop that minimum, because you no longer know the minimum before it and must rescan. Consider keeping the older minima instead of discarding them.
Hint 2 The minimum only changes at pushes and pops, and after a pop it returns to exactly what it was before the popped element arrived. History that unwinds in LIFO order fits naturally in another stack.
Hint 3 Alongside each element (or in a parallel stack), record the minimum of everything at or below it. `getMin` reads the top of that record; `pop` discards it in lockstep. Both are O(1).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug