Implement Queue using Stacks
Easy
Topics
Implement a first-in-first-out (FIFO) queue using only two stacks. Implement MyQueue with push(x), pop() (removes and returns the front element), peek() (returns the front element), and empty().
Example 1
The visible behaviour must be a queue — oldest element out first — while the only storage permitted is stacks, which give the newest back first. Every operation has to answer exactly as a real queue would.
Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["MyQueue","push","push","peek","pop","empty"], values = [[],[1],[2],[],[],[]] Output: [null,null,null,1,1,false]
Constraints
- 1 <= x <= 9
- At most 100 calls to push, pop, peek, and empty.
- pop and peek are only called on a non-empty queue.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A stack is LIFO but a queue is FIFO. Use an input stack for pushes and an output stack for pops. When the output stack is empty, pour the input stack into it — this reverses the order so the oldest element ends up on top.
Approach
- push always goes onto the input stack.
- For pop/peek, if the output stack is empty, move every element from input to output (reversing order).
- The front of the queue is then the top of the output stack.
Dry Run
MyQueue()
push 1 -> null inp [1] out []
push 3 -> null inp [1, 3] out []
pop -> 1 inp [] out [3] out was empty, so pour: 3 lands
first, then 1 on top; pop takes 1
peek -> 3 inp [] out [3] out is not empty, no pour
push 1 -> null inp [1] out [3] the new 1 waits in inp
pop -> 3 inp [1] out [] out still held the 3, no pour
pop -> 1 inp [] out [] out empty, pour the 1 across
push 3 -> null inp [3] out []
empty -> false inp [3] out []
pop -> 3 inp [] out []
push 8 -> null inp [8] out []
empty -> false inp [8] out []
answer null|null|null|1|3|null|3|1|null|false|3|null|false
The "push 1" on row 5 is the row that justifies the only-when-empty rule. At that
instant out holds [3] and inp holds [1]. The 3 is older and has to leave first;
pouring inp across right then would stack the newer 1 on top of it and the next
pop would wrongly return 1. Waiting until out drains keeps the two halves ordered
without ever recording arrival times.
Each element crosses from inp to out exactly once in its life, which is where the
amortized O(1) comes from. The one expensive pop that pours k elements has already
been paid for by the k pushes that put them there.Complexity
- Time — O(1) amortized: each element is moved between stacks at most once.
- Space — O(n): the two stacks hold all queued elements.
Common Pitfalls
- Only refill the output stack when it is empty; refilling early scrambles the order.
Full Solution — all languages
class MyQueue:
def __init__(self):
self.inp = []
self.out = []
def push(self, x):
self.inp.append(x)
def _shift(self):
if not self.out:
while self.inp:
self.out.append(self.inp.pop())
def pop(self):
self._shift()
return self.out.pop()
def peek(self):
self._shift()
return self.out[-1]
def empty(self):
return not self.inp and not self.outimport java.util.*;
class MyQueue {
Deque<Integer> inp = new ArrayDeque<>();
Deque<Integer> out = new ArrayDeque<>();
public MyQueue() {
}
public void push(int x) {
inp.push(x);
}
private void shift() {
if (out.isEmpty()) {
while (!inp.isEmpty()) out.push(inp.pop());
}
}
public int pop() {
shift();
return out.pop();
}
public int peek() {
shift();
return out.peek();
}
public boolean empty() {
return inp.isEmpty() && out.isEmpty();
}
}#include <bits/stdc++.h>
using namespace std;
class MyQueue {
stack<int> inp, out;
void shift() {
if (out.empty()) {
while (!inp.empty()) {
out.push(inp.top());
inp.pop();
}
}
}
public: MyQueue() {
}
void push(int x) {
inp.push(x);
}
int pop() {
shift();
int v = out.top();
out.pop();
return v;
}
int peek() {
shift();
return out.top();
}
bool empty() {
return inp.empty() && out.empty();
}
};class MyQueue {
constructor() {
this.inp = [];
this.out = [];
}
push(x) {
this.inp.push(x);
}
_shift() {
if (this.out.length === 0) {
while (this.inp.length) this.out.push(this.inp.pop());
}
}
pop() {
this._shift();
return this.out.pop();
}
peek() {
this._shift();
return this.out[this.out.length - 1];
}
empty() {
return this.inp.length === 0 && this.out.length === 0;
}
}
Asked at
Qualcomm