#225

Implement Stack using Queues

Easy Rotate on push

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

?The problem

Build a LIFO stack (push, pop, top, empty) using only queue operations.

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

◎Understanding

Really asking: LIFO behaviour from a queue.

Why this works: after adding x, rotate the older items behind it, so x is at the front.

Example: push 1, push 2

[1] → add 2 → [1, 2] → rotate → [2, 1]pop → 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using a Deque's stack methods (push/pop) — that defeats the exercise. Stick to offer/poll/peek.

Solve on LeetCode ↗
Complexity
  • Time: push O(n), pop/top O(1).
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon