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).
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.
Input: ["MessageQueue","empty"] [[],[]] Output: [null,true]
A new queue is empty.
1 <= message <= 9100 calls.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).
I'm here to help with #277 Two-Stack Message Queue. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.