 All Problems
Min Stack
easy
stack
design
amazon
google
microsoft

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

  • push(val) — pushes val onto the stack.
  • pop() — removes the element on top of the stack.
  • top() — gets the top element.
  • getMin() — retrieves the minimum element in the stack.

Example:

Input:
push 5
push 3
push 7
getMin
top
pop
getMin

Output:
3
7
3

Constraints:

  • -2³¹ ≤ val ≤ 2³¹ − 1
  • pop, top, and getMin operations will always be called on a non-empty stack.
  • At most 3 × 10⁴ calls total.

Input format: One command per line. push X pushes integer X. pop removes top. top prints the top element. getMin prints the current minimum.

Output format: Print a result line only for top and getMin commands.

Run to check your code against the sample cases, or submit to run every case