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 toppop()- Remove and return the top elementtop()- View the top element without removing itempty()- 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code