Skip to the code
cf.
+25 XP

#9 Two-Stack Task Queue

medium

A background job runner keeps its queue in two arrays used as stacks: inbox and outbox. A ["push", x] operation pushes x onto inbox. A ["pop"] operation takes the oldest job: if outbox is empty, it first moves every item from inbox to outbox one at a time (popping from inbox and pushing onto outbox), then pops from outbox.

Write runQueue(ops) that performs the operations in order and returns { popped, moves }: popped lists what each pop returned, in order, and moves counts the items moved from inbox to outbox in total. A pop on an empty queue returns -1 and moves nothing.

Example 1

Input: ops = [["push",1],["push",2],["pop"],["push",3],["pop"],["pop"]]
Output: {"popped":[1,2,3],"moves":3}

The first pop moves 1 and 2 to outbox. The second pop uses outbox as is. The third finds it empty and moves 3.

Example 2

Input: ops = [["pop"]]
Output: {"popped":[-1],"moves":0}

Both stacks are empty, so the pop returns -1.

Constraints

  • 0 <= ops.length <= 10^5
  • Pushed values are whole numbers from 0 to 10^9.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).