Skip to content

visual walkthrough

Implement Queue using Stacks

EasyTwo StacksReported at: AmazonMicrosoftGoogle+1

Amortised O(1) with two stacks; a common design warm-up.

Solve on LeetCode

The idea

A queue is first-in-first-out, a stack is last-in-first-out. Pouring one stack into another reverses the order, which turns LIFO into FIFO.

Pour only when the second stack runs dry. Each item is moved at most once, so the cost per operation averages out to O(1).

Complexity

approachtimespace
Reshuffle on every pushO(n) pushO(n)
Two stacks, pour lazilyO(1) amortisedO(n)

More walkthroughs