Skip to content
Onsite

Queue Using Two Stacks

EasyP1Coding

Implement a first-in, first-out queue using only two stacks (arrays used with push and pop at the end only).

Implement the MyQueue class:

  • MyQueue() creates an empty queue.
  • push(x) adds x to the back of the queue.
  • pop() removes the element at the front and returns it.
  • peek() returns the element at the front without removing it.
  • empty() returns true if the queue has no elements.

pop and peek are only called on a non-empty queue. Each operation should run in amortised O(1).

Example 1

Input
["MyQueue","push","push","peek","pop","empty"] [[],[1],[2],[],[],[]]
Output
[null,null,null,1,1,false]
Why
After push(1), push(2) the front is 1. pop() returns 1, leaving 2, so the queue is not empty.

Constraints

  • 1 <= x <= 10^9
  • At most 100 calls to push, pop, peek and empty.
  • pop and peek are only called when the queue is non-empty.

Hints

Run checks the 3 visible tests, Submit all 5.