Implement Stack using Queues - Problem

Imagine you're a data structure architect tasked with creating a stack (Last-In-First-Out) using only queues (First-In-First-Out) as your building blocks!

A stack supports these operations:

  • push(x) - Add element to the top
  • pop() - Remove and return the top element
  • top() - View the top element without removing it
  • empty() - Check if the stack is empty

The challenge? You can only use standard queue operations:

  • Add to back of queue
  • Remove from front of queue
  • Check size and emptiness

This is like trying to make a plate dispenser (stack) work using only a cafeteria line system (queue)!

Input & Output

example_1.py โ€” Basic Operations
$ Input: ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []]
โ€บ Output: [null, null, null, 2, 2, false]
๐Ÿ’ก Note: Create stack, push 1 and 2, check top (should be 2 since it was last pushed), pop (returns and removes 2), check if empty (false since 1 is still there)
example_2.py โ€” Single Element
$ Input: ["MyStack", "push", "pop", "empty"] [[], [1], [], []]
โ€บ Output: [null, null, 1, true]
๐Ÿ’ก Note: Create stack, push 1, pop it (returns 1), check if empty (true since no elements remain)
example_3.py โ€” Multiple Operations
$ Input: ["MyStack", "push", "push", "push", "top", "pop", "top", "pop", "top"] [[], [1], [2], [3], [], [], [], [], []]
โ€บ Output: [null, null, null, null, 3, 3, 2, 2, 1]
๐Ÿ’ก Note: Shows LIFO behavior: push 1,2,3 then operations return elements in reverse order (3,2,1)

Constraints

  • 1 โ‰ค x โ‰ค 109
  • At most 100 calls will be made to push, pop, top, and empty
  • All calls to pop and top are guaranteed to be valid (stack won't be empty)

Visualization

Tap to expand
Queue โ†’ Stack TransformationQueue (FIFO)123serveServes: 1, 2, 3Stack (LIFO)312serveServes: 3, 2, 1Rotate!๐Ÿ’ก Key InsightPush: O(1) - Just add to queuePop: O(n) - Rotate to access last element
Understanding the Visualization
1
Normal Queue Behavior
In a regular queue, first person in line gets served first (FIFO)
2
Stack Requirement
We need the last person to join to be served first (LIFO)
3
The Rotation Solution
When serving, rotate everyone except the last person, serve them, then continue
4
Efficient for Adding
New people can join instantly, complexity only comes when serving
Key Takeaway
๐ŸŽฏ Key Insight: We can simulate any data structure using another, but the choice of which operations to optimize depends on the expected usage pattern. For write-heavy workloads, optimizing push over pop makes practical sense!
Asked in
Amazon 42 Microsoft 38 Google 28 Meta 22
68.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen