Implement Queue using Stacks

easy

Implement a first-in-first-out queue using only stacks (LIFO structures). Support:

  • push(x) — push x to the back of the queue.
  • pop() — remove and return the front element.
  • peek() — return the front element without removing it.
  • empty() — return whether the queue is empty.

pop and peek are only called on a non-empty queue. Use only standard stack operations (push, pop/top, size/empty).

Hints

A stack is LIFO but a queue needs FIFO — how does pouring one stack into another help?
Pouring input into output reverses the order, putting the oldest element on top.
Only transfer when the output stack is empty; that keeps it amortized O(1).

Common doubts

If output still holds elements, they're already in front-first order. Pouring again would re-reverse them and break FIFO.
Each element is moved from input to output at most once in its lifetime, so the total transfer work across all operations is O(n) — amortized O(1) each.
One stack can only reverse once; you'd have to reverse back and forth on every operation. The second stack caches the reversed order so you reverse each element only once.

Interview follow-ups

Yes — a push-costly variant keeps the queue reversed on every push, making pop/peek O(1) but push O(n). The two-stack lazy version is usually preferred.
Purely functional (immutable) queues use exactly this front-list / back-list pair, reversing the back list onto the front when it empties.

Fun facts

  • The two-stack queue is the classic example of amortized analysis in algorithms courses.
  • Immutable/persistent queues in functional languages are built from this very front/back pair of stacks.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: push(1), push(2), peek(), pop(), empty()
Output: 1, 1, false
peek and pop both return 1 (the oldest); after popping, 2 remains, so empty is false.
Example 2
Input: push(5), pop(), empty()
Output: 5, true
Push then pop returns 5, leaving the queue empty.
Constraints

- 1 <= x <= 10^5 - At most 100 operations. - pop and peek are only called on a non-empty queue.

Solve this problem →