In computer science, a queue follows the First-In-First-Out (FIFO) principle, while a stack follows Last-In-First-Out (LIFO). This article explores how to implement a queue using two stacks, comparing a brute force approach with an optimized solution that achieves amortized O(1) time complexity for push and pop operations.
Brute Force Approach
The simplest method is to keep one stack as the primary storage. For a push operation, we transfer all elements from the primary stack to a secondary stack, add the new element, then move everything back. This ensures the newest element is at the bottom, maintaining FIFO order.
public void push(int x) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
s1.push(x);
while (!s2.isEmpty()) {
s1.push(s2.pop());
}
}
While this works, the push operation takes O(n) time, making it inefficient for frequent inserts.
Optimized Approach (Amortized O(1))
The optimized solution uses two stacks: an input stack and an output stack. The key insight is to defer the reversal until it's needed.
- Push: Always push to the input stack.
- Pop/Peek: If the output stack is empty, transfer all elements from input to output (reversing order), then pop/peek from the output stack.
public void push(int x) {
input.push(x);
}
public int pop() {
if (output.isEmpty()) {
while (!input.isEmpty()) {
output.push(input.pop());
}
}
return output.pop();
}
Each element is moved at most twice (once into input, once into output), resulting in O(1) amortized time for each operation.
Complexity Analysis
| Approach | Push | Pop | Peek |
|---|---|---|---|
| Brute Force | O(n) | O(1) | O(1) |
| Optimized | O(1) amortized | O(1) amortized | O(1) amortized |
Key Takeaway
The optimized approach demonstrates a classic trade-off: by using two stacks and lazily moving elements, we achieve efficient average-case performance while maintaining correctness. This pattern appears frequently in coding interviews and real-world applications.