Skip to content
DeepForgeby svx
All problems
HardData Structuresds-004

Min Stack with O(1) Minimum

Problem

Design a stack that supports push, pop, top, and retrieving the minimum element, all in O(1) time.

operations contains "push", "pop", "top", or "get_min"; values provides the pushed value and is ignored for other operations. Record None for push and pop, the top value (or None if empty) for top, and the current minimum (or None if empty) for get_min.

Return the list of recorded results.

Hint

Keep a second stack whose top always holds the minimum seen so far.

Test cases

case 1
in: [["push","push","push","get_min","pop","top","get_min"],[5,3,7,0,0,0,0]]
expected: [null,null,null,3,null,3,3]
case 2
in: [["push","get_min","push","get_min","pop","get_min"],[1,0,0,0,0,0]]
expected: [null,1,null,0,null,1]
case 3
in: [["pop","get_min"],[0,0]]
expected: [null,null]
case 4
in: [["push","pop","get_min"],[1,0,0]]
expected: [null,null,null]
Starter codePython
def min_stack(operations, values):
    # Your code here
    pass

4 test cases · run your code against them in the editor