Skip to content
Decoder

Implement Queue using Stacks

Easy

Problem

Build a first-in, first-out queue class MyQueue using only two stacks (lists used only with push to the end, pop from the end, look at the end, and size). It supports:

- push(x) adds x to the back of the queue. - pop() removes the front element and returns it. - peek() returns the front element without removing it. - empty() returns whether the queue is empty.

Example 1

q = MyQueue()

Example 2

q.push(1); q.push(2)

Example 3

Input
q.peek()
Output
1

Example 4

Input
q.pop()
Output
1

Example 5

Input
q.empty()
Output
false

Each operation should take amortised O(1) time.

Constraints

  • 1 <= x <= 9
  • At most 100 calls are made in total.
  • pop and peek are only called on a non-empty queue.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.