DIGITAL GURU
Java DSA Portfolio

Queue using Stacks

Implement a FIFO Queue using two LIFO Stacks (Input Stack & Output Stack).

Anuj Kumar Singh Written by Anuj Kumar Singh (Lead Engineer, 13+ yrs exp) 5 min read Verified Spring Boot 3+ Guide

Real-World Analogy

Queue using 2 Stacks is like pouring a stack of numbered books from Bucket A into Bucket B—flipping them upside down so the bottom book is now on top!

Two-Stack Queue Mechanics

Push goes to `input` stack. Pop/Peek transfers elements from `input` to `output` stack, reversing order to achieve FIFO behavior in $O(1)$ amortized time.

Production Code Example:

MyQueue.java
import java.util.Stack;
public class MyQueue {
    private Stack<Integer> in = new Stack<>(), out = new Stack<>();
    public void push(int x) { in.push(x); }
    public int pop() {
        peek(); return out.pop();
    }
    public int peek() {
        if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop());
        return out.peek();
    }
}

Key Complexity & Algorithmic Takeaways:

When implementing Queue using Stacks in coding interviews and production applications, keep these core guidelines in mind:

  • Time Complexity Analysis: Always evaluate best-case, average-case, and worst-case time complexities ($O(1)$, $O(\log n)$, $O(n)$, $O(n \log n)$, $O(n^2)$).
  • Space Complexity & Memory Bounds: Account for auxiliary memory usage, call stack frame recursion overhead, and heap allocations.
  • Edge Cases & Validation: Test empty inputs, null pointers, single-element collections, duplicate values, and integer overflow bounds.
  • Optimal vs Naive Solutions: Start with a clear brute-force solution, then optimize using techniques like Hashing, Two Pointers, Windowing, or Dynamic Programming.

Summary Takeaway:

Mastering Queue using Stacks provides the foundational problem-solving skills needed to pass technical coding interviews at top tech companies and write ultra-performant software systems.

Amortized Analysis

`pop()` runs in $O(1)$ amortized time because each element is moved at most twice.