Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #232: Implement Queue using Stacks

In this guide, we solve Leetcode #232 Implement Queue using Stacks in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Quick Facts

  • Difficulty: Easy
  • Premium: No
  • Tags: Stack, Design, Queue

Intuition

The problem has a natural nested or last-in-first-out structure.

A stack lets us resolve matches in the correct order as we scan.

Approach

Push items as they appear and pop when you can finalize a decision.

The stack captures the unresolved part of the input.

Steps:

  • Push elements as you scan.
  • Pop when a rule or match is satisfied.
  • Use the stack to compute results.

Example

Input ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 1, 1, false] Explanation MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false

Python Solution

class MyQueue: def __init__(self): self.stk1 = [] self.stk2 = [] def push(self, x: int) -> None: self.stk1.append(x) def pop(self) -> int: self.move() return self.stk2.pop() def peek(self) -> int: self.move() return self.stk2[-1] def empty(self) -> bool: return not self.stk1 and not self.stk2 def move(self): if not self.stk2: while self.stk1: self.stk2.append(self.stk1.pop()) # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()

Complexity

The time complexity is O(1)O(1)O(1). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy