CodingNodes / Stack / Min Stack System design Space play · ←→ step · R restart

Problem

Build a class MinStack that works like an ordinary stack of integers but can also report its smallest element at any moment. It needs these operations:

  • MinStack() creates an empty stack.
  • push(val) puts val on top.
  • pop() throws away the top element.
  • top() returns the top element without removing it.
  • getMin() returns the smallest element currently in the stack.

Every one of these must run in constant time, O(1). The input is a list of calls and their arguments; the output lists what each call returns (null for the constructor and for calls with no return value).

Constraints

  • −2³¹ ≤ val ≤ 2³¹ − 1
  • pop, top and getMin are only called when the stack is not empty
  • At most 3 · 10⁴ calls in total

Examples: pick one to animate

Solutions

TimeO(1) SpaceO(n)

Time: Each call does a fixed number of push, pop or peek operations on the two stacks.

Space: The main stack holds all n values, and the min stack holds at most n of them.

Keep a second stack whose top is always the current minimum. Push onto it when the new value is less than or equal to its top (so duplicate minimums are kept), and pop from it when the value leaving the main stack equals its top.