Course contents

Stack algorithms with ArrayDeque

Stack algorithms with ArrayDeque, balanced brackets, undo-redo, monotonic stacks, RPN, min-stack, iterative DFS and histogram rectangles.

PremiumMust know for interviewsLesson13 min readCoreReviewed Oct 2026 · Java 21
On this page
  1. Picture it first: unfinished work on top
  2. Balanced brackets under the hood
  3. Undo-redo: two stacks working together
  4. Monotonic stack: next greater and daily temperatures
  5. Reverse Polish Notation: evaluate as values become ready
  6. Min-stack: one stack for values, one for current minimums
  7. Iterative DFS: avoid deep recursion when the input can be tall
  8. Senior stretch: largest rectangle in a histogram
  9. Advanced: edge cases and pitfalls
  10. How to say it in the interview

📚 What are stack algorithms with ArrayDeque?

A stack algorithm keeps unfinished work in last-in, first-out order: the last thing opened is the first thing resolved. Think of a stack of plates, except each plate might be an opening bracket, an undo action, a graph node, or an index waiting for a warmer day. In Java, the modern shape is Deque<E> stack = new ArrayDeque<>();, then push, pop and peek.

For this lesson, we'll focus on the stack patterns you should recognize in interviews and write cleanly in Java 21: balanced brackets, undo-redo, monotonic stacks, Reverse Polish Notation, min-stack, iterative DFS and the histogram rectangle stretch. We will use ArrayDeque as the stack, but we will not repeat its circular-array internals here; those live in Queue, Deque and ArrayDeque.

Below the line (out of scope)

  • Deque internals, method families and why ArrayDeque beats LinkedList: Queue, Deque and ArrayDeque
  • Heap-based priority questions: Top-K with a heap
  • Graph traversal with FIFO order belongs to BFS; here we use a stack for DFS and backtracking.
  • Concurrency is deliberately out of scope. ArrayDeque is not thread-safe.

The 30-second answer

Use a stack when the newest unresolved item must be handled first: nested brackets, expression evaluation, undo, DFS backtracking, previous or next greater elements. In modern Java, prefer Deque<E> stack = new ArrayDeque<>(); over java.util.Stack for ordinary single-threaded code because Stack is a legacy Vector subclass. push adds to the front, pop removes the front, and peek inspects it. Most stack algorithms are O(n) because every item is pushed once and popped once. Guard empty pops because pop() throws NoSuchElementException, remember ArrayDeque rejects null, and know that iterating an ArrayDeque used as a stack visits the top first.

What you’ll learn

  • Recognize LIFO clues: nesting, last-opened-first-resolved, undo, backtracking and next-greater prompts
  • Use Deque<E> stack = new ArrayDeque<>() instead of legacy Stack for ordinary Java stack work
  • Implement balanced brackets and explain the top-of-stack invariant with a walkthrough
  • Build undo-redo, Reverse Polish Notation, min-stack and iterative DFS patterns
  • Solve monotonic stack questions such as next greater element and Daily Temperatures in amortized O(n)
  • Name stack pitfalls: empty pops, null rejection, iteration order and deep-recursion limits

01Picture it first: unfinished work on top

A stack is a pile of unfinished promises. When you see {[()]}, every opener waits until its matching closer arrives. The innermost opener, (, is on top, so it must be resolved before [ and {.

That is the mental model: last opened, first resolved.

Fig. 1

Balanced bracket scanning pushes opening brackets and pops the most recent matching opener when a closer arrives

Balanced bracket scanning pushes opening brackets and pops the most recent matching opener when a closer arrives

Interviewers love this pattern because it is small enough to code quickly and subtle enough to test whether you understand the invariant. The invariant is not "I have seen some brackets". It is sharper: the stack contains unmatched opening brackets, top first, in the only order they can still be closed.

02Balanced brackets under the hood

Try it yourself first

Before reading the code, walk through {[()]}. What is on top of the stack when the ) arrives?

Here is how I'd write the core bracket checker. This version ignores non-bracket characters, which is a choice you should state if the prompt includes arbitrary text.

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;

final class BalancedBracketsDemo {
    static boolean isValidBrackets(String input) {
        Deque<Character> stack = new ArrayDeque<>();
        Map<Character, Character> openingForClosing = Map.of(
                ')', '(',
                ']', '[',
                '}', '{'
        );

        for (char ch : input.toCharArray()) {
            if (ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch);
            } else if (openingForClosing.containsKey(ch)) {
                if (stack.isEmpty() || stack.pop() != openingForClosing.get(ch)) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isValidBrackets("{[()]}")); // true
    }
}

Notice three things:

  • We check isEmpty() before pop() because empty pop() throws NoSuchElementException.
  • We compare the closing bracket to the most recent unmatched opener, not to any opener seen earlier.
  • We return stack.isEmpty() at the end because leftover openers mean the input ended too early.

For {[()]}, the walkthrough is short enough to narrate while coding:

Character Action Stack, top first
{ push opener {
[ push opener [ {
( push opener ( [ {
) pop matching ( [ {
] pop matching [ {
} pop matching { empty

If the input is ([)], the ) sees [ on top. That is the bug the stack catches: the right bracket exists, but the nesting order is wrong.

Premium lesson

Keep reading with the Java Pass

The rest of this lesson is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.

  • Undo-redo: two stacks working together
  • Monotonic stack: next greater and daily temperatures
  • Reverse Polish Notation: evaluate as values become ready
  • Min-stack: one stack for values, one for current minimums
  • Iterative DFS: avoid deep recursion when the input can be tall
  • Senior stretch: largest rectangle in a histogram
  • Advanced: edge cases and pitfalls
  • How to say it in the interview

From ₹199 · one-time payment · No auto-renewal

Practise this topicCollections in action: interview questions & scenarios
Further reading (6)