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 queue
  • int pop() Removes the element from the front of the queue and returns it
  • int peek() Returns the element at the front of the queue
  • boolean 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
Queue Using Two Stacks: FIFO with LIFO ComponentsInput Stack (LIFO)push(1)1push(2)2Transfer whenoutput emptyOutput Stack (LIFO)12pop() → 1peek() → 1FIFO Queue BehaviorFirst In: 1, 2First Out: 1, then 2✓ Correct order achieved!Input Stack + Output Stack = QueueTwo LIFO structures combine to create one FIFO structure
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
Asked in
Amazon 45 Microsoft 32 Apple 28 Google 25
185.0K Views
High Frequency
~25 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