Data Structures & Algorithms Queues & Deques
💡
Exercise 77

Queue Using Stacks 20 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Implement a queue using only two stacks. This classic problem teaches how data structures can simulate each other.

q = MyQueue() q.push(1) # stack_in: [1] q.push(2) # stack_in: [1, 2] q.peek() # → 1 (front of queue) q.pop() # → 1 (FIFO) q.empty() # → False

The two-stack trick:

  • stack_in: Always push new elements here
  • stack_out: Pop from here for dequeue/peek
  • When stack_out is empty, dump all of stack_in into stack_out (reverses order!)
  • LIFO + LIFO = FIFO — reversing twice gives you queue order

Amortized O(1) per operation — each element is moved at most twice (once into stack_in, once into stack_out).

📋 Instructions
Implement MyQueue using two stacks. Test push, peek, pop, and empty operations.
push() always appends to stack_in. For pop/peek, if stack_out is empty, transfer ALL elements from stack_in to stack_out (pop from stack_in, push to stack_out). Then pop/peek from stack_out.
🧪 Test Cases
Input
q.peek()
Expected
1
Test case 1
Input
q.pop()
Expected
1
Test case 2
Input
q.empty()
Expected
False
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.