Skip to the code
cf.
+10 XP

#277 Two-Stack Message Queue

easy

A web worker bridge can only use stacks (arrays with push, pop, a length, and reading the last item), but messages must be delivered in the order they were sent. Write a class MessageQueue using only those stack operations:

  • push(message) adds a message to the back.
  • pop() removes and returns the oldest message.
  • peek() returns the oldest message without removing it.
  • empty() returns whether there are no messages.

pop and peek are only called when the queue is not empty. Each call should be O(1) on average.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new MessageQueue(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["MessageQueue","push","push","peek","pop","empty"]
[[],[1],[2],[],[],[]]
Output: [null,null,null,1,1,false]

1 was sent first, so it is peeked and popped first; 2 is still waiting.

Example 2

Input: ["MessageQueue","empty"]
[[],[]]
Output: [null,true]

A new queue is empty.

Constraints

  • 1 <= message <= 9
  • At most 100 calls.
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).