Skip to main content
Back to problems
Leetcode
Medium
Stacks
Queues
Design
Implement Queue Using Stacks

Design a FIFO queue using only stack operations.

Acceptance 100%
Problem Statement

Problem

Implement a queue data structure using only stack operations. Your queue should support the standard FIFO behavior while relying on stacks internally.

Create a class that supports the following operations:

  • push(x): add an element to the back of the queue
  • pop(): remove and return the element at the front of the queue
  • peek(): return the front element without removing it
  • empty(): return whether the queue has no elements

You may use one or more stacks to build the queue, but you should not use any built-in queue implementation.

The key challenge is to preserve queue order while only having stack access, which naturally works in LIFO order.

Input Format

  • Operations are performed on a queue object.
  • push(x) receives one integer x.
  • pop(), peek(), and empty() take no extra arguments.

Output Format

  • push(x) updates the internal state and returns nothing.
  • pop() returns the front element.
  • peek() returns the current front element.
  • empty() returns true if the queue contains no elements, otherwise false.

Constraints

  • Implement the queue using stack operations only.
  • Assume all operations are called in a valid order for the chosen API.
  • Aim for efficient amortized performance across a sequence of operations.
Examples
Sample cases returned by the problem API.

Example 1

Input

["MyQueue","push","push","peek","pop","empty"]
[[],[1],[2],[],[],[]]

Output

[null,null,null,1,1,false]

Explanation

After pushing 1 and 2, the front of the queue is 1. peek() returns 1 without removing it, pop() removes 1, and the queue is still not empty because 2 remains.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.