#232

Implement Queue using Stacks

Easy Two stacks

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Build a FIFO queue (push, pop, peek, empty) using only stack operations.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: FIFO behaviour from LIFO stacks.

Why this works: pouring one stack into another reverses the order. Pour only when the "out" stack is empty.

Example: push 1, push 2, pop

in [1, 2] → pour → out [2, 1] (1 on top)pop → 1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Pouring from in to out on every pop even when out isn't empty — that breaks the order.

Solve on LeetCode ↗
Complexity
  • Time: Amortised O(1) per operation.
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon