Menu
CoddyTech

Implement Queue Using Stacks

EasyQueueStackpython iconjava iconcpp iconc iconjs icon+10

Build a first in, first out queue whose only storage is two stacks. A stack may only add an item on top, remove the top item, read the top item and tell whether it is empty. The queue supports push x (add x at the back), pop (remove and return the front item), peek (return the front item) and empty (is the queue empty?).

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 queue that starts empty and return one string per operation: "null" for a push, the number as text for a pop or a peek, and "true" or "false" for empty.

Function

queueOps(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 ≤ 2000
  • args.length == ops.length
  • Every ops[i] is push, pop, peek or empty.
  • -109 ≤ args[i] ≤ 109 for a push, and args[i] == 0 for any other operation.
  • pop and peek are only called when the queue holds at least one item.

Examples

Input
ops = ["push", "push", "peek", "pop", "empty"]args = [1, 2, 0, 0, 0]
Output
["null", "null", "1", "1", "false"]
Explanation
After pushing 1 and then 2, the front is 1, so peek and pop both return "1". The 2 is still inside, so empty returns "false".

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

How would you add a back operation that returns the newest item in O(1), without breaking the amortized bound of the others?

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

Case 1

Case 2

Case 3

Input

ops = ["push", "push", "peek", "pop", "empty"]
args = [1, 2, 0, 0, 0]

Expected

["null", "null", "1", "1", "false"]