Skills101
← All coding problems

Min Stack

mediumStack & Queue+20 XPTime limit 2s

Build a stack that also returns its minimum element in O(1):

  • push x — push x
  • pop — remove the top element (print nothing)
  • top — print the top element
  • getMin — print the smallest element currently in the stack

Input:

  • line 1: q
  • next q lines: one operation each. pop, top and getMin are only used when the stack is not empty.

Output: one line for every top and getMin.

Constraints: 1 ≤ q ≤ 10⁵, −2³¹ ≤ x ≤ 2³¹ − 1.

The trick: store, next to every value, the minimum of the stack at the moment it was pushed. Popping then automatically restores the previous minimum. Scanning the whole stack on every getMin is O(n) — too slow for the big tests.

Sample input 1

7
push -2
push 0
push -3
getMin
pop
top
getMin

Sample output 1

-3
0
-2

Sample input 2

3
push 5
top
getMin

Sample output 2

5
5

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.