Skip to content
Decoder

Min Stack

Medium

Problem

Build a class MinStack that works like a normal stack but can also report its **smallest value in O(1) time**. Every method must run in O(1).

- push(val) adds val to the top. - pop() removes the top value and returns it. - top() returns the top value without removing it. - get_min() in Python, getMin() in TypeScript, returns the smallest value currently in the stack.

Example 1

s = MinStack()

Example 2

s.push(-2); s.push(0); s.push(-3)

Example 3

Input
s.get_min()
Output
-3

Example 4

Input
s.pop()
Output
-3

Example 5

Input
s.top()
Output
0

Example 6

Input
s.get_min()
Output
-2

Constraints

  • -2^31 <= val <= 2^31 - 1
  • pop, top and get_min are only called on a non-empty stack.
  • At most 3 * 10^4 calls are made in total.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.