← Back to DSA
#232
Implement Queue using Stacks
Implement Queue using Stacks solution for LeetCode 232, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Implement Queue using Stacks
Why it belongs on this sheet
This problem is useful because it pushes you to explain amortized complexity clearly, not just code mechanics.
Pattern
Input stack plus output stack
Approach
Push everything into the input stack. Only when the output stack is empty, move all input elements across so their order reverses and queue front becomes available.
Java solution
import java.util.ArrayDeque;
import java.util.Deque;
class MyQueue {
private final Deque<Integer> in = new ArrayDeque<>();
private final Deque<Integer> out = new ArrayDeque<>();
public void push(int x) {
in.push(x);
}
public int pop() {
moveIfNeeded();
return out.pop();
}
public int peek() {
moveIfNeeded();
return out.peek();
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
private void moveIfNeeded() {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
}
}
Complexity
- Amortized time per operation:
O(1) - Space:
O(n)
Interview note
Be ready to justify amortized O(1) instead of worst-case O(n) for a single transfer.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)