15% off all plans & roadmaps Use code
See plansImplement Stack using Queues
- LeetCode 225
- Easy
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: You must build a LIFO stack from queues that only allow push to back and pop from front. Keep the newest element at the front by rotating the queue after each push, so pop and top run in O(1).
Problem
Implement a last-in-first-out (LIFO) stack using only two queues. The stack must support push, top, pop, and empty, the same operations a normal stack offers.
Implement the MyStack class:
void push(int x)pushes element x to the top of the stack.int pop()removes the element on the top of the stack and returns it.int top()returns the element on the top of the stack.boolean empty()returnstrueif the stack is empty,falseotherwise.
Notes:
- You must use only standard queue operations. That means push to back, peek or pop from front, size, and is empty.
- Your language may not provide a queue natively. You may simulate one with a list or deque, as long as you use only standard queue operations.
Example 1
Input: ["MyStack", "push", "push", "top", "pop", "empty"] and [[], [1], [2], [], [], []] Output: [null, null, null, 2, 2, false] Explanation: Create the stack, push 1, then push 2. top() returns 2. pop() returns 2. empty() returns false because 1 is still in the stack.
Constraints
1 <= x <= 9- At most
100calls will be made topush,pop,top, andempty. - All calls to
popandtopare valid.
Constraints that matter
- Each
popandtopcall is valid, so you never need to handle an empty stack in those methods. - At most 100 calls means the stack holds at most 100 elements, so a method that costs O(n) per push is fast enough.
- Values are between 1 and 9, so you do not need to think about overflow or special values.
Hints
Hint 1
A stack returns the newest element first.
Hint 2
Keep two queues.
Solution
Intuition
A stack returns the newest element first. A queue returns the oldest element first. The problem asks you to build last-in, first-out behaviour from a first-in, first-out container, so the real question is where the newest element can wait until it reaches the front.
Picture a queue as a checkout line where people join at the back and leave from the front. Each push is a newcomer joining, then everyone already waiting walks to the back one at a time, so the newcomer reaches the front.
This is an adapter pattern. You wrap one data structure in a class that exposes a different interface. Every method must work using only the queue's allowed operations, and that restriction decides the design.
The key observation is that a queue can rotate. Enqueue the new value, then dequeue and re-enqueue each older value once. The new value ends up at the front, and the older values stay in their original order behind it. After that, pop and top are each one queue operation.
Worked example
Input: commands: ["MyStack", "empty"], args: [[], []] Output: [null, true] Explanation: The constructor runs first and creates an empty stack. Calling empty() on that stack returns true. The dry runs below extend this example with a push, top, pop and empty sequence on the same object.
Approach 1: Two queues, copy on push
Keep two queues. The first queue, q1, holds the stack with the top at its front. The second queue, q2, is an empty helper between calls.
To push, add the new value to q2 first, then move every element of q1 behind it. Now the new value is at the front of q2 and the older values follow in order. Swap the two queues so that q1 is the stack again. Pop and top read the front of q1.
This is correct, and it is the natural first design. It copies the whole stack on every push, even though the stack changes by only one element. The helper queue exists only to hold that copy.
Steps
- Create two empty queues, q1 and q2.
- In push, enqueue x into q2.
- While q1 is not empty, dequeue from q1 and enqueue into q2.
- Swap the names of q1 and q2 so q1 holds the full stack again.
- In pop, dequeue from the front of q1 and return it.
- In top, return the front of q1 without removing it.
- In empty, return whether q1 has no elements.
Dry run
Start with q1 = [] and q2 = [] and run the example sequence push(1), push(2), top(), pop(), empty().
The lists below run from front to back.
| Call | Action | q1 after | q2 after | Return |
|---|---|---|---|---|
| MyStack() | create both queues | [] | [] | |
| empty() | q1 has no elements | [] | [] | true |
| push(1) | q2 gets 1, q1 is empty, swap | [1] | [] | |
| push(2) | q2 gets 2, then 1 moves from q1, swap | [2, 1] | [] | |
| top() | read front of q1 | [2, 1] | [] | 2 |
| pop() | remove front of q1 | [1] | [] | 2 |
| empty() | q1 still holds 1 | [1] | [] | false |
The example output [null, true] comes from the first empty() call on the fresh stack.
Complexity
| Time | push O(n), pop O(1), top O(1), empty O(1) |
|---|---|
| Space | O(n) |
Let n be the number of elements in the stack when you push. Push enqueues x into q2, then moves all n older elements from q1 to q2, about n + 1 queue operations of O(1) each, so push is O(n). Pop, top and empty each touch the front of one queue once, so they are O(1). Across both queues there are at most n stored elements, so space is O(n).
PythonTested in our runner
from typing import List, Optional
from collections import deque
class MyStack:
def __init__(self):
# q1 holds the stack, q2 is the helper
self.q1 = deque()
self.q2 = deque()
def push(self, x: int) -> None:
self.q2.append(x)
while self.q1:
self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1
def pop(self) -> int:
return self.q1.popleft()
def top(self) -> int:
return self.q1[0]
def empty(self) -> bool:
return len(self.q1) == 0JavaTested in our runner
import java.util.*;
class MyStack {
private Queue<Integer> q1;
private Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q2.add(x);
while (!q1.isEmpty()) {
q2.add(q1.remove());
}
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
}
public int pop() {
return q1.remove();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}C++Tested in our runner
#include <queue>
#include <utility>
class MyStack {
public:
std::queue<int> q1;
std::queue<int> q2;
MyStack() {
}
void push(int x) {
q2.push(x);
while (!q1.empty()) {
q2.push(q1.front());
q1.pop();
}
std::swap(q1, q2);
}
int pop() {
int v = q1.front();
q1.pop();
return v;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();
}
};JavaScriptTested in our runner
var MyStack = function() {
this.q1 = [];
this.q2 = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.q2.push(x);
while (this.q1.length > 0) {
this.q2.push(this.q1.shift());
}
[this.q1, this.q2] = [this.q2, this.q1];
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
return this.q1.shift();
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
return this.q1[0];
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return this.q1.length === 0;
};GoTested in our runner
type MyStack struct {
q1 []int
q2 []int
}
func Constructor() MyStack {
return MyStack{q1: []int{}, q2: []int{}}
}
func (this *MyStack) push(x int) {
this.q2 = append(this.q2, x)
for len(this.q1) > 0 {
this.q2 = append(this.q2, this.q1[0])
this.q1 = this.q1[1:]
}
this.q1, this.q2 = this.q2, this.q1
}
func (this *MyStack) pop() int {
v := this.q1[0]
this.q1 = this.q1[1:]
return v
}
func (this *MyStack) top() int {
return this.q1[0]
}
func (this *MyStack) empty() bool {
return len(this.q1) == 0
}C#Tested in our runner
public class MyStack {
private Queue<int> q1 = new Queue<int>();
private Queue<int> q2 = new Queue<int>();
public MyStack() {
}
public void push(int x) {
q2.Enqueue(x);
while (q1.Count > 0) {
q2.Enqueue(q1.Dequeue());
}
Queue<int> tmp = q1;
q1 = q2;
q2 = tmp;
}
public int pop() {
return q1.Dequeue();
}
public int top() {
return q1.Peek();
}
public bool empty() {
return q1.Count == 0;
}
}The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: One queue, rotate on pushOptimalDesign (General/Specific)
What's slow in the two-queue version is the helper queue. It exists only to hold a temporary copy of the stack, and every push pays to copy everything.
The insight that fixes it is that you do not need a copy. After you enqueue x at the back, the other n-1 elements are still in the queue in newest-to-oldest order. If you dequeue each of them from the front and enqueue it at the back, x moves forward past all of them and becomes the front. The relative order of the older elements stays the same.
Since the front is always the newest element, pop and top become single queue operations. All the work moves to push, where it is paid once per element.
Steps
- Create one queue q.
- In push, enqueue x at the back of q.
- Let n be the size of q. Repeat n-1 times: dequeue the front and enqueue it at the back.
- In pop, dequeue and return the front of q.
- In top, return the front of q without removing it.
- In empty, return whether q has no elements.
Dry run
Run the same sequence on one queue: push(1), push(2), top(), pop(), empty(). The lists run from front to back.
| Step | Call | Queue before rotation | Rotation work | Queue after | Return |
|---|---|---|---|---|---|
| 0 | MyStack() | [] | none | [] | |
| 1 | empty() | [] | none | [] | true |
| 2 | push(1) | [1] | n-1 = 0 moves | [1] | |
| 3 | push(2) | [1, 2] | n-1 = 1 move: dequeue 1, enqueue 1 | [2, 1] | |
| 4 | top() | [2, 1] | none | [2, 1] | 2 |
| 5 | pop() | [2, 1] | none | [1] | 2 |
| 6 | empty() | [1] | none | [1] | false |
Row 1 produces the example output's first value, true. Row 3 shows the single rotation that brings 2 to the front.
Complexity
| Time | push O(n), pop O(1), top O(1), empty O(1) |
|---|---|
| Space | O(n) |
Let n be the number of elements in the stack when you push. Push enqueues one element and then performs n-1 dequeue and enqueue pairs, about 2n queue operations of O(1) each, so push is O(n). Pop, top and empty each perform one front operation, so they are O(1). The queue stores n elements and the rotation uses no other storage, so space is O(n).
PythonTested in our runner
from typing import List, Optional
from collections import deque
class MyStack:
def __init__(self):
self.q = deque()
def push(self, x: int) -> None:
self.q.append(x)
# Move the n-1 older elements behind x so x reaches the front
for _ in range(len(self.q) - 1):
self.q.append(self.q.popleft())
def pop(self) -> int:
return self.q.popleft()
def top(self) -> int:
return self.q[0]
def empty(self) -> bool:
return len(self.q) == 0JavaTested in our runner
import java.util.*;
class MyStack {
private Queue<Integer> q;
public MyStack() {
q = new LinkedList<>();
}
public void push(int x) {
q.add(x);
int n = q.size();
// Move the n-1 older elements behind x
for (int i = 0; i < n - 1; i++) {
q.add(q.remove());
}
}
public int pop() {
return q.remove();
}
public int top() {
return q.peek();
}
public boolean empty() {
return q.isEmpty();
}
}C++Tested in our runner
#include <queue>
class MyStack {
public:
std::queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
int n = q.size();
// Move the n-1 older elements behind x
for (int i = 0; i < n - 1; i++) {
q.push(q.front());
q.pop();
}
}
int pop() {
int v = q.front();
q.pop();
return v;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};JavaScriptTested in our runner
var MyStack = function() {
this.q = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.q.push(x);
for (let i = 0; i < this.q.length - 1; i++) {
this.q.push(this.q.shift());
}
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
return this.q.shift();
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
return this.q[0];
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return this.q.length === 0;
};GoTested in our runner
type MyStack struct {
q []int
}
func Constructor() MyStack {
return MyStack{q: []int{}}
}
func (this *MyStack) push(x int) {
this.q = append(this.q, x)
n := len(this.q)
// Move the n-1 older elements behind x
for i := 0; i < n-1; i++ {
this.q = append(this.q[1:], this.q[0])
}
}
func (this *MyStack) pop() int {
v := this.q[0]
this.q = this.q[1:]
return v
}
func (this *MyStack) top() int {
return this.q[0]
}
func (this *MyStack) empty() bool {
return len(this.q) == 0
}C#Tested in our runner
public class MyStack {
private Queue<int> q = new Queue<int>();
public MyStack() {
}
public void push(int x) {
q.Enqueue(x);
int n = q.Count;
// Move the n-1 older elements behind x
for (int i = 0; i < n - 1; i++) {
q.Enqueue(q.Dequeue());
}
}
public int pop() {
return q.Dequeue();
}
public int top() {
return q.Peek();
}
public bool empty() {
return q.Count == 0;
}
}Common mistakes
- Rotating
ntimes instead ofn-1in the one-queue push. After n rotations the queue is back in its original order, so x stays at the back. Rotate exactly n-1 times. - Reading
q.back()intop(). A queue exposes only the front for reads, and the stack top is the front in the one-queue design. - Computing the rotation count inside the loop condition with a changing size, such as
while (q.size() > 1)with a counter that never resets. Read n once before the loop and run n-1 steps. - Using
list.pop(0)as the dequeue in Python. Removing from the front of a Python list costs O(n), which turns every pop into O(n). Usecollections.dequewithpopleft. - In the two-queue version, swapping the local names but not the fields or references, so the next call reads the empty queue. Update the stored queues after the swap.
Edge cases
- Call
empty()on a new stack. The answer is true, and no queue operation should fail. - Push one value, then pop it. The stack is empty afterwards, and
empty()returns true. In the one-queue design, the rotation runs zero times for the first push. - Push the same value twice, such as 5 then 5. Both copies stay in the stack, and two pops return 5 and then 5.
- Push up to 100 values, then pop them all. The last pop returns the first value pushed, and every value comes back in reverse order.
- Push, pop, then push again. The new value must become the top, and it must not return an old value left in the queue.
Follow-ups interviewers ask
- Can you make push O(1) and pay the cost in pop instead?
- Yes. Keep the queue in plain insertion order and let pop rotate the queue until the newest element reaches the front. Pop then costs O(n) and top still needs the back element, which means a rotation too. The total work across operations stays in the same order, so the choice depends on which call the caller makes more often.
- Can you implement the stack using only one queue?
- Yes. The one-queue rotation approach on this page does exactly that. It keeps one queue, rotates it on each push, and reads the front for top and pop.
- What if the stack must hold millions of values?
- Memory is still O(n), and that cannot change for a stack of n values. The rotation cost becomes the bottleneck, because each push moves up to n values. At that scale you would use a real stack or a ring buffer and skip the rotation entirely.
Implement Stack using Queues FAQ
What is the time complexity of Implement Stack using Queues?
Push is O(n) in the one-queue design, where n is the current stack size, because it rotates n-1 elements. Pop, top and empty are each O(1). The two-queue design has the same bounds.
Why use queue rotation for Implement Stack using Queues?
Rotation moves the newest element to the front of the queue, which is the only position a queue lets you read or remove. Once the newest element is at the front, every stack operation maps to a single queue operation. The adapter pattern makes this possible without any random access.
Can Implement Stack using Queues be solved in O(1) extra space?
Yes, in the sense that the rotation uses only one temporary value and no auxiliary structure. The stored elements still take O(n) space, because the stack must hold them. The two-queue version uses a second queue, which is also O(n) in the worst case.
Why does Python need deque for this problem?
A Python list removes from the front in O(n), so each pop or rotation step would cost linear time. A deque supports popleft and append in O(1). Using a deque keeps the queue operations constant time.
Asked at
See which companies ask this — Pro
Related problems
- Design HashMap · same technique: Design (General/Specific)
- Implement Queue using Stacks · same technique: Design (General/Specific)
- Logger Rate Limiter · same technique: Design (General/Specific)
- Moving Average from Data Stream · same technique: Design (General/Specific)
- Design Compressed String Iterator · same technique: Design (General/Specific)
- LRU Cache · next harder, same pattern
- Longest Word in Dictionary · same pattern: Design Patterns
- Min Stack · same pattern: Design Patterns
- Time Based Key-Value Store · same pattern: Design Patterns
- Encode and Decode Strings · same pattern: Design Patterns