Menu
CoddyTech

Min Stack

MediumStackpython iconjava iconcpp iconc iconjs icon+10

Design a stack that, besides the usual push, pop and top, can report the smallest value it holds with getMin. Each of the four operations must run in O(1) time.

You get the operations in order as ops, with args[i] holding the value for a push and 0 for every other operation. Run them on one stack that starts empty and return one string per operation: "null" for push and pop, and the number as text for top and getMin.

Function

minStackOps(ops: string-array, args: integer-array) → string-array
opsstring-array
the operations, in the order they run
argsinteger-array
the value for each push, 0 for every other operation
Returnsstring-array
one answer per operation, as text

Constraints

  • 1 ≤ ops.length ≤ 3000
  • args.length == ops.length
  • Every ops[i] is push, pop, top or getMin.
  • -231+1 ≤ args[i] ≤ 231-1 for a push, and args[i] == 0 for any other operation.
  • pop, top and getMin are only called when the stack holds at least one value.

Examples

Input
ops = ["push", "push", "push", "getMin", "pop", "top", "pop", "getMin"]args = [4, 1, 7, 0, 0, 0, 0, 0]
Output
["null", "null", "null", "1", "null", "1", "null", "4"]
Explanation
The stack holds 4, 1 and 7 from the bottom up, so the smallest is 1. Popping 7 leaves 1 on top. Popping 1 as well leaves only 4, so the minimum goes back to 4.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

Can you build a first in, first out queue that also reports its minimum in O(1) amortized time?

Reset code
def minStackOps(ops, args):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

ops = ["push", "push", "push", "getMin", "pop", "top", "pop", "getMin"]
args = [4, 1, 7, 0, 0, 0, 0, 0]

Expected

["null", "null", "null", "1", "null", "1", "null", "4"]