15% off all plans & roadmaps Use code
See plansImplement Queue using Stacks
- LeetCode 232
- Easy
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Build a first-in, first-out queue using only stack operations. Keep one stack for pushes and one for pops, and move elements across only when the output stack runs empty.
Problem
You need a first in, first out (FIFO) queue built from stacks. Your class must support push, pop, peek, and empty.
You may use only stack operations: push to top, peek or pop from top, size, and is-empty. A Python list or a deque can stand in for a stack, as long as you touch only the top.
Implement the MyQueue class:
void push(int x)pushes element x to the back of the queue.int pop()removes the element at the front of the queue and returns it.int peek()returns the element at the front of the queue.boolean empty()returnstrueif the queue is empty,falseotherwise.
Example 1
Input: ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] Output: [null, null, null, 1, 1, false] Explanation: After the first push the queue is [1]. After the second push it is [1, 2], with 1 at the front. peek returns 1. pop returns 1, leaving [2]. empty returns false.
Constraints
1 <= x <= 9- At most
100calls will be made topush,pop,peek, andempty. - All calls to
popandpeekare valid.
Constraints that matter
- At most 100 calls means brute force finishes well within limits, so the real test is the amortized bound the follow-up asks for.
- Values are between 1 and 9, so a plain int stack holds every value. The values themselves never affect the algorithm.
- Every
popandpeekcall is valid. You never need an error branch for an empty queue in those methods. - Only stack operations are allowed. Removing from the front of a list costs O(n), and a deque's front removal breaks the rule.
Hints
Hint 1
A stack returns the newest element first, and a queue returns the oldest element first.
Hint 2
A beginner keeps one stack whose top is the front of the queue.
Solution
Intuition
A stack returns the newest element first, and a queue returns the oldest element first. Pushing values onto one stack and then popping them onto a second stack reverses their order. That reversal is the step you need.
It is like flipping a stack of unsorted mail onto a second pile. The input stack is the incoming pile, and the output stack is the pile you read from, so the oldest letter sits on top.
This is a design problem. You wrap two stacks behind a fixed interface, and the real decision is when to move data between them. Pick that moment carefully and the moves average out to constant time per call. That averaging is amortized analysis, and it is what the follow-up asks for.
The statement restricts you to stack operations, so you cannot index into a list or remove from its front. The stacks must do the reordering for you. Reorder only when a read forces it. Once an element reaches the output stack, it stays there until it leaves.
Worked example
Input: operations = ["MyQueue", "empty"], values = [[], []] Output: [null, true] Explanation: The constructor runs first and returns null. The new queue has no elements, so empty() returns true. Both stacks are empty at that point.
Approach 1: Brute force: rebuild on every push
A beginner keeps one stack whose top is the front of the queue. A push then has to place the new value at the bottom, because it is the newest and belongs at the back. The only way to reach the bottom is to lift every element off, put the new value down, and place the old elements back on top. The pop and peek methods then read the top directly.
Steps
- Keep one stack
stackwhere the top holds the front of the queue. - In
push, pop every element offstackonto a helper stack. - Push
xontostack. It is the only element there, so it sits at the bottom. - Pop everything from the helper back onto
stack. The old front returns to the top. popandpeekread or remove the top.emptychecks whetherstackhas elements.
Dry run
The page example has no pushes, so start with the empty stack. A new MyQueue has stack = [], and empty() returns true. The output is [null, true], which matches the verified example.
For a trace with pushes, use Example 1 from the statement. After push(1) the stack holds [1], with 1 on top. For push(2), the 1 moves to the helper, the 2 goes down, and the 1 returns on top, so the stack reads [2, 1] from bottom to top. peek() returns 1. pop() returns 1 and leaves [2]. empty() returns false. The output is [null, null, null, 1, 1, false].
Complexity
| Time | O(n) per push, O(1) for pop, peek, and empty |
|---|---|
| Space | O(n) |
Let n be the number of elements in the queue. A push moves each of the n elements to the helper and back, which is about 2n stack operations. The pop, peek, and empty methods touch only the top, so each does constant work. The two stacks hold n values in total, so the space is O(n).
PythonTested in our runner
class MyQueue:
def __init__(self):
# The top of this list is the front of the queue
self.stack = []
def push(self, x: int) -> None:
helper = []
# Move everything aside so x can sit at the bottom
while self.stack:
helper.append(self.stack.pop())
self.stack.append(x)
while helper:
self.stack.append(helper.pop())
def pop(self) -> int:
return self.stack.pop()
def peek(self) -> int:
return self.stack[-1]
def empty(self) -> bool:
return len(self.stack) == 0JavaTested in our runner
import java.util.*;
class MyQueue {
// The top of this stack is the front of the queue
private Deque<Integer> stack = new ArrayDeque<>();
public MyQueue() {
}
public void push(int x) {
Deque<Integer> helper = new ArrayDeque<>();
while (!stack.isEmpty()) {
helper.push(stack.pop());
}
stack.push(x);
while (!helper.isEmpty()) {
stack.push(helper.pop());
}
}
public int pop() {
return stack.pop();
}
public int peek() {
return stack.peek();
}
public boolean empty() {
return stack.isEmpty();
}
}C++Tested in our runner
#include <stack>
class MyQueue {
// The top of this stack is the front of the queue
std::stack<int> s;
public:
MyQueue() {
}
void push(int x) {
std::stack<int> helper;
while (!s.empty()) {
helper.push(s.top());
s.pop();
}
s.push(x);
while (!helper.empty()) {
s.push(helper.top());
helper.pop();
}
}
int pop() {
int v = s.top();
s.pop();
return v;
}
int peek() {
return s.top();
}
bool empty() {
return s.empty();
}
};JavaScriptTested in our runner
var MyQueue = function() {
// The end of this array is the front of the queue
this.stack = [];
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
const helper = [];
while (this.stack.length > 0) {
helper.push(this.stack.pop());
}
this.stack.push(x);
while (helper.length > 0) {
this.stack.push(helper.pop());
}
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
return this.stack.pop();
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
return this.stack[this.stack.length - 1];
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.stack.length === 0;
};GoTested in our runner
type MyQueue struct {
stack []int // the end of this slice is the front of the queue
}
func Constructor() MyQueue {
return MyQueue{stack: []int{}}
}
func (this *MyQueue) push(x int) {
helper := []int{}
for len(this.stack) > 0 {
helper = append(helper, this.stack[len(this.stack)-1])
this.stack = this.stack[:len(this.stack)-1]
}
this.stack = append(this.stack, x)
for len(helper) > 0 {
this.stack = append(this.stack, helper[len(helper)-1])
helper = helper[:len(helper)-1]
}
}
func (this *MyQueue) pop() int {
top := this.stack[len(this.stack)-1]
this.stack = this.stack[:len(this.stack)-1]
return top
}
func (this *MyQueue) peek() int {
return this.stack[len(this.stack)-1]
}
func (this *MyQueue) empty() bool {
return len(this.stack) == 0
}C#Tested in our runner
public class MyQueue {
// The top of this stack is the front of the queue
private Stack<int> stack = new Stack<int>();
public MyQueue() {
}
public void push(int x) {
Stack<int> helper = new Stack<int>();
while (stack.Count > 0) {
helper.Push(stack.Pop());
}
stack.Push(x);
while (helper.Count > 0) {
stack.Push(helper.Pop());
}
}
public int pop() {
return stack.Pop();
}
public int peek() {
return stack.Peek();
}
public bool empty() {
return stack.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: Two stacks with lazy transferOptimalDesign (General/Specific)
What's slow: the brute force rebuilds the whole stack on every push, even when nobody reads the queue. Most of that work is wasted, because a value that is only pushed never needs to reach the front.
The insight that fixes it: keep pushes on an input stack with no reordering at all. Move elements to an output stack only when pop or peek needs the front and the output stack is empty.
The transfer reverses the input once, so the oldest element lands on top. Elements stay on the output stack until they leave.
Why it is correct. The invariant is that the output stack holds the oldest elements in reading order, and every element in the input stack is newer than all of them. When outStack is empty, moving everything from inStack reverses the input, so the oldest element ends on top. Elements already on outStack never need to move again, so its top is always the correct front.
Steps
- Create
inStackfor pushes andoutStackfor reads. - In
push(x), pushxontoinStackand do nothing else. - In
popandpeek, ifoutStackis empty, pop everything frominStackand push each value ontooutStack. - In
pop, pop and return the top ofoutStack. Inpeek, return that top without removing it. - In
empty, return true only when both stacks are empty.
Dry run
The page example, verified, is empty() on a new queue. The table has one row per step.
| Step | Call | inStack (bottom to top) | outStack (bottom to top) | Returns |
|---|---|---|---|---|
| 0 | constructor | [] | [] | null |
| 1 | empty() | [] | [] | true |
The output is [null, true].
For Example 1 from the statement, the trace is longer:
| Step | Call | inStack | outStack | Returns |
|---|---|---|---|---|
| 1 | push(1) | [1] | [] | null |
| 2 | push(2) | [1, 2] | [] | null |
| 3 | peek(), outStack empty, move 2 then 1 | [] | [2, 1] | 1 |
| 4 | pop(), outStack not empty, pop its top | [] | [2] | 1 |
| 5 | empty(), outStack still holds 2 | [] | [2] | false |
The output is [null, null, null, 1, 1, false].
Complexity
| Time | O(1) amortized for push, pop, peek, and empty. A single pop or peek can take O(n). |
|---|---|
| Space | O(n) |
Let n be the number of pushes in a sequence of calls. Each value moves from inStack to outStack at most once, and it never moves back. A transfer costs time proportional to the number of values it moves, so all transfers together cost at most n moves. Spreading the O(n) total over the calls gives O(1) amortized per call, and the two stacks hold at most n values, so the space is O(n).
PythonTested in our runner
class MyQueue:
def __init__(self):
self.input_stack = [] # new elements land here
self.output_stack = [] # the top is the front of the queue
def push(self, x: int) -> None:
self.input_stack.append(x)
def _transfer_if_needed(self) -> None:
# Move elements only when the front is needed and output is empty
if not self.output_stack:
while self.input_stack:
self.output_stack.append(self.input_stack.pop())
def pop(self) -> int:
self._transfer_if_needed()
return self.output_stack.pop()
def peek(self) -> int:
self._transfer_if_needed()
return self.output_stack[-1]
def empty(self) -> bool:
return not self.input_stack and not self.output_stackJavaTested in our runner
import java.util.*;
class MyQueue {
private Deque<Integer> inStack = new ArrayDeque<>();
private Deque<Integer> outStack = new ArrayDeque<>();
public MyQueue() {
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
transferIfNeeded();
return outStack.pop();
}
public int peek() {
transferIfNeeded();
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
// Move everything only when outStack is empty
private void transferIfNeeded() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
}
}C++Tested in our runner
#include <stack>
class MyQueue {
std::stack<int> inStack; // new elements land here
std::stack<int> outStack; // the top is the front of the queue
void transferIfNeeded() {
if (outStack.empty()) {
while (!inStack.empty()) {
outStack.push(inStack.top());
inStack.pop();
}
}
}
public:
MyQueue() {
}
void push(int x) {
inStack.push(x);
}
int pop() {
transferIfNeeded();
int v = outStack.top();
outStack.pop();
return v;
}
int peek() {
transferIfNeeded();
return outStack.top();
}
bool empty() {
return inStack.empty() && outStack.empty();
}
};JavaScriptTested in our runner
var MyQueue = function() {
this.inStack = []; // new elements land here
this.outStack = []; // the end of this array is the front of the queue
};
MyQueue.prototype.transferIfNeeded = function() {
if (this.outStack.length === 0) {
while (this.inStack.length > 0) {
this.outStack.push(this.inStack.pop());
}
}
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.inStack.push(x);
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
this.transferIfNeeded();
return this.outStack.pop();
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
this.transferIfNeeded();
return this.outStack[this.outStack.length - 1];
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.inStack.length === 0 && this.outStack.length === 0;
};GoTested in our runner
type MyQueue struct {
inStack []int // new elements land here
outStack []int // the end of this slice is the front of the queue
}
func Constructor() MyQueue {
return MyQueue{inStack: []int{}, outStack: []int{}}
}
func (this *MyQueue) transferIfNeeded() {
if len(this.outStack) == 0 {
for len(this.inStack) > 0 {
top := this.inStack[len(this.inStack)-1]
this.inStack = this.inStack[:len(this.inStack)-1]
this.outStack = append(this.outStack, top)
}
}
}
func (this *MyQueue) push(x int) {
this.inStack = append(this.inStack, x)
}
func (this *MyQueue) pop() int {
this.transferIfNeeded()
top := this.outStack[len(this.outStack)-1]
this.outStack = this.outStack[:len(this.outStack)-1]
return top
}
func (this *MyQueue) peek() int {
this.transferIfNeeded()
return this.outStack[len(this.outStack)-1]
}
func (this *MyQueue) empty() bool {
return len(this.inStack) == 0 && len(this.outStack) == 0
}C#Tested in our runner
public class MyQueue {
private Stack<int> inStack = new Stack<int>();
private Stack<int> outStack = new Stack<int>();
public MyQueue() {
}
public void push(int x) {
inStack.Push(x);
}
public int pop() {
TransferIfNeeded();
return outStack.Pop();
}
public int peek() {
TransferIfNeeded();
return outStack.Peek();
}
public bool empty() {
return inStack.Count == 0 && outStack.Count == 0;
}
// Move everything only when outStack is empty
private void TransferIfNeeded() {
if (outStack.Count == 0) {
while (inStack.Count > 0) {
outStack.Push(inStack.Pop());
}
}
}
}Common mistakes
- Moving elements back to
inStackafter each read, for exampleinStack.push(outStack.pop())insidepop. Each call then costs O(n). Keep elements onoutStackuntil they leave. - Transferring when
outStackis not empty, for exampleif inStack is not emptyinsidepop. Newer elements land on top of older ones, so the front is wrong. Transfer only whenoutStackis empty. - Checking only
inStackinempty, as inreturn not inStack. Elements still waiting onoutStackare queued. Check both stacks. - Reading the front with
list[0]or removing it withpop(0). That costs O(n) and breaks the stack-only rule. Read the top with[-1]or the stack's peek. - Putting the transfer only in
pop, not inpeek. Thenpeekreturns a stale value from the input side or fails on an empty output stack. Call one shared helper from both methods. - Pushing new values straight onto
outStack. The new value lands on top, which is the front, sopopreturns the newest value instead of the oldest.
Edge cases
- A single push followed by a pop:
push(5), thenpop()returns 5, andempty()returns true afterwards. - A
peekbetween pushes:push(1),peek()returns 1,push(2),pop()returns 1, thenpop()returns 2. - Repeated values:
push(3)twice, then two pops return 3 and 3. Order follows insertion time, not value. - Draining the queue: after
popemptiesoutStack,empty()must still return false whileinStackholds values. empty()on a new queue: returns true with no transfer and no reads.- A long run of up to 100 pushes followed by 100 pops: the values come back in the exact order they went in.
Follow-ups interviewers ask
- Why is the amortized bound O(1) when one pop can cost O(n)?
- A transfer moves every element in the input stack at once, and that can be many elements. Each element crosses from the input stack to the output stack once and never comes back. So the total number of moves across all calls is at most the number of pushes. Spreading that total over the calls gives O(1) each.
- Can you solve it with one stack and recursion instead?
- Yes. To remove the oldest element, recurse until you reach the bottom of the stack, take that value, and push the rest back on the way up. Each pop costs O(n), and deep recursion can overflow the call stack for large queues. The two stack version keeps the amortized bound and avoids deep recursion.
- What changes if several threads call these methods?
- Both
popandpeekcan move elements and changeoutStack, so a single lock around each method is the safe choice. Without a lock, two threads can interleave a transfer and corrupt both stacks. A lock-free design is much harder and is not needed for this problem.
Implement Queue using Stacks FAQ
What is the time complexity of Implement Queue using Stacks?
With the lazy transfer, push is O(1), and pop, peek, and empty are O(1) amortized. A single pop can take O(n) when it moves elements. Over a sequence of n calls the total work is O(n).
Why use two stacks for Implement Queue using Stacks?
A stack reverses order, and two reversals restore first-in, first-out order. The input stack stores new values without reordering them. The output stack gives you the oldest value on top after each transfer.
Can Implement Queue using Stacks be solved in O(1) extra space?
No, the queue must hold all of its values, so total space is O(n). Beyond those stored values, the lazy approach needs no extra container, so its auxiliary space is O(1). The brute force approach also uses only the two stacks it needs, so both stay within O(n) total.
Can I use Python's deque for Implement Queue using Stacks?
A deque with popleft would solve the problem in one line, but the statement allows only stack operations. Use a list with append and pop() from the end, both of which are O(1). Calling pop(0) on a list is O(n) and will be slow on large inputs.
What is the difference between Implement Queue using Stacks and Implement Stack using Queues?
The first problem reverses order with two stacks, while the second reverses order with queues. Both use a transfer step to flip the order. The stack-from-queue version needs to rotate elements on every push in its simple form.
Asked at
See which companies ask this — Pro
Related problems
- Design HashMap · same technique: Design (General/Specific)
- Implement Stack using Queues · 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