Implement Queue using Stacks - Problem
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue.
Implement the MyQueue class:
void push(int x)Pushes element x to the back of the queueint pop()Removes the element from the front of the queue and returns itint peek()Returns the element at the front of the queueboolean empty()Returns true if the queue is empty, false otherwise
Notes:
- You must use only standard operations of a stack (push to top, peek/pop from top, size, and is empty)
- Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque as long as you use only a stack's standard operations
Input & Output
Example 1 — Basic Queue Operations
$
Input:
operations = ["MyQueue", "push", "push", "peek", "pop", "empty"], values = [null, 1, 2, null, null, null]
›
Output:
[null, null, null, 1, 1, false]
💡 Note:
Create queue, push 1 and 2, peek returns 1 (front), pop returns 1, queue not empty (still has 2)
Example 2 — Multiple Operations
$
Input:
operations = ["MyQueue", "push", "push", "push", "pop", "pop", "empty"], values = [null, 1, 2, 3, null, null, null]
›
Output:
[null, null, null, null, 1, 2, false]
💡 Note:
Push 1,2,3 then pop twice: first pop gets 1, second pop gets 2, queue still has 3 so not empty
Example 3 — Empty Queue Check
$
Input:
operations = ["MyQueue", "push", "pop", "empty"], values = [null, 5, null, null]
›
Output:
[null, null, 5, true]
💡 Note:
Push 5, pop 5, now queue is empty so empty() returns true
Constraints
- 1 ≤ x ≤ 9
- At most 100 calls will be made to push, pop, peek, and empty
- All the calls to pop and peek are valid
Visualization
Tap to expand
Understanding the Visualization
1
Input
Operations and values for queue implementation
2
Two Stack System
Input stack for push, output stack for pop/peek
3
FIFO Result
Queue operations return correct FIFO order
Key Takeaway
🎯 Key Insight: Use input stack for push, output stack for pop/peek with lazy transfer
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code