Java Data Structure Program · OT39
Implement a Queue Using Two Stacks in Java
Pouring one stack into another reverses its order. So push new items onto an input stack, and serve items from an output stack that is refilled only when it runs empty.
Problem Statement
Implement a queue with enqueue and dequeue using only two stacks.
Items must leave in the order they arrived, and dequeue on an empty queue must throw an exception.
Input/Output Examples
enqueue 1, 2, 3; dequeue()Output1Explanation: the oldest item leaves first.enqueue 4; dequeue() three timesOutput2, 3, 4Explanation: 4 waits until the older items have left.dequeue() on an empty queueOutputexception: queue is emptyExplanation: nothing to return.Visual Explanation
- enqueue 1, 2, 3in123outpush onto in
- dequeue()inout321out is empty: pour in into out pop 1
- enqueue 4in4out32out still has items
- dequeue()out32pop 2, no transfer
Each item is moved from in to out at most once, so although a single dequeue can move many items, the average cost per operation is constant.
Approaches
Both versions give the same order. The lazy version transfers only when needed; the eager version keeps the stack in queue order at all times.
Approach 1: Lazy Transfer (Recommended)
Idea: push onto in; when out is empty, move everything from in to out, then pop from out.
enqueue:in.push(x).dequeue: ifoutis empty, pour all ofininto it.- Pop from
out, or throw if it is still empty.
Time: O(1) amortised · Space: O(n).
Approach 2: Eager Transfer on Enqueue
Idea: on every enqueue, move all items to a temporary stack, push the new item, and move them back, so the oldest item is always on top.
- Move
mainintotemp. - Push the new item onto
main. - Move
tempback;dequeueis then a single pop.
Time: O(n) per enqueue · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Lazy Transfer (Recommended)
This is the version interviewers expect, together with the amortised argument.
import java.util.ArrayDeque;
import java.util.Deque;
public class QueueTwoStacksLazy {
// in receives new items; out serves them; refill out only when it is empty
static class MyQueue {
private final Deque<Integer> in = new ArrayDeque<>();
private final Deque<Integer> out = new ArrayDeque<>();
void enqueue(int x) {
in.push(x);
}
int dequeue() {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop()); // reverses the order: oldest on top
}
}
if (out.isEmpty()) {
throw new IllegalStateException("queue is empty");
}
return out.pop();
}
}
public static void main(String[] args) {
MyQueue q = new MyQueue();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
System.out.println("dequeue() = " + q.dequeue());
q.enqueue(4);
System.out.println("dequeue() = " + q.dequeue());
System.out.println("dequeue() = " + q.dequeue());
System.out.println("dequeue() = " + q.dequeue());
try {
q.dequeue();
} catch (IllegalStateException e) {
System.out.println("dequeue() on empty -> " + e.getMessage());
}
}
}
dequeue() = 1 dequeue() = 2 dequeue() = 3 dequeue() = 4 dequeue() on empty -> queue is empty
Time complexity: O(1) amortised · Space complexity: O(n).
Approach 2: Eager Transfer on Enqueue
Simple to reason about, but every enqueue costs linear time.
import java.util.ArrayDeque;
import java.util.Deque;
public class QueueTwoStacksEager {
// Keeps the oldest item on top of main at all times by moving everything on each enqueue
static class MyQueue {
private final Deque<Integer> main = new ArrayDeque<>();
private final Deque<Integer> temp = new ArrayDeque<>();
void enqueue(int x) {
while (!main.isEmpty()) {
temp.push(main.pop());
}
main.push(x);
while (!temp.isEmpty()) {
main.push(temp.pop());
}
}
int dequeue() {
if (main.isEmpty()) {
throw new IllegalStateException("queue is empty");
}
return main.pop();
}
}
public static void main(String[] args) {
MyQueue q = new MyQueue();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
System.out.println("dequeue() = " + q.dequeue());
q.enqueue(4);
System.out.println("dequeue() = " + q.dequeue());
System.out.println("dequeue() = " + q.dequeue());
System.out.println("dequeue() = " + q.dequeue());
try {
q.dequeue();
} catch (IllegalStateException e) {
System.out.println("dequeue() on empty -> " + e.getMessage());
}
}
}
dequeue() = 1 dequeue() = 2 dequeue() = 3 dequeue() = 4 dequeue() on empty -> queue is empty
Time complexity: O(n) per enqueue · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Lazy Transfer | O(1) amortised | O(n) |
| Eager Transfer on Enqueue | O(n) per enqueue | O(n) |
Here n is the number of items. In the lazy version each item is pushed and popped twice in total, giving amortised O(1); the eager version pays O(n) on every enqueue.
Interview Tips and Recommended Approach
- Transfer only when
outis empty. Transferring earlier breaks the order. - Explain amortised analysis: each element moves between stacks at most once.
- Know the reverse question. A stack from two queues needs
O(n)push or pop. - Use
ArrayDequefor both stacks in Java.
Recommended Approach: Lazy Transfer
Why: it gives constant average time per operation and is the classic example of amortised analysis.