Java stack and queue interview programs: valid parentheses, reverse a queue, binary numbers

A stack hands back the last thing you put in. A queue hands back the first. Three classic problems show when each one is the right tool, and why modern Java code uses ArrayDeque for both instead of the old Stack class.

Checking the string {[()]} with a stack, in six steps. Reading {, [ and ( pushes the matching closing brackets }, ] and ) onto the stack, which grows to three items with ) on top. Then reading ), ] and } each pops a matching bracket off the top, marked with a tick, until the stack is empty. Red marks the top of the stack, what peek() returns. A dark bar shows Deque<Character> stack = new ArrayDeque<>(), and says empty at the end means valid.
Fig. 1 — Push what you expect to see later. Pop it when it arrives. Empty at the end means every bracket matched.

Some problems are about the order you process things in. Two simple structures cover most of them:

  • A stack is like a pile of plates. You put a plate on top (push) and take from the top (pop). Last in, first out: LIFO.
  • A queue is like a line at a ticket counter. People join at the back (add) and leave from the front (poll). First in, first out: FIFO.

Use ArrayDeque for both

Java has an old Stack class from Java 1.0. Don’t use it in new code. It extends Vector, so every method is synchronized (slow for no reason), and it lets you insert into the middle, which a stack shouldn’t allow. Even its own documentation recommends Deque instead.

A Deque (“deck”, a double-ended queue) can add and remove at both ends, so it works as a stack and a queue. ArrayDeque is the implementation to use:

Deque<Character> stack = new ArrayDeque<>();   // as a stack
Queue<String> queue = new ArrayDeque<>();      // as a queue

Make that first line your default stack. Interviewers notice.

As a stack As a queue What it does
push(x) add(x) / offer(x) put an element in
pop() poll() take one out (pop throws if empty, poll returns null)
peek() peek() look at the next one without removing it
isEmpty() isEmpty() anything left?

One small catch: ArrayDeque doesn’t allow null elements. You’ll never need them for these problems.

23. Valid parentheses

Problem: a string holds only (, ), [, ], { and }. It’s valid if every opening bracket is closed by the same type, in the right order.

"()[]{}"  → true
"{[]}"    → true
"([)]"    → false   ( is closed by ] before ) arrives
"("       → false   never closed
")"       → false   closed before it was opened

Why a stack? The most recently opened bracket must be the first one closed. “Most recent first” is exactly what a stack gives you.

Plan, with a neat trick: when you see an opening bracket, push the closing bracket you now expect. When you see a closing bracket, pop the stack and check it’s the one you expected.

static boolean isValid(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        if (c == '(') stack.push(')');
        else if (c == '[') stack.push(']');
        else if (c == '{') stack.push('}');
        else if (stack.isEmpty() || stack.pop() != c) return false;
    }
    return stack.isEmpty();
}

The picture at the top walks through "{[()]}" step by step.

There are three ways to fail, and the code catches all of them:

  1. A closing bracket with nothing open, like ")": the stack is empty, so stack.isEmpty() returns false before we try to pop.
  2. The wrong closing bracket, like "(]": we pop ) but see ].
  3. Brackets left open, like "(": the loop ends with something still on the stack, so return stack.isEmpty() gives false.

Is stack.pop() != c safe? pop() returns a Character object and c is a char, so Java unboxes the Character and compares the values. That’s fine. (Comparing two Character objects with != would not be.)

The map version

Some people find a map easier to read, and it’s easier to extend with new bracket types:

static boolean isValid(String s) {
    Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{');
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        if (pairs.containsValue(c)) {           // an opening bracket
            stack.push(c);
        } else if (pairs.containsKey(c)) {      // a closing bracket
            if (stack.isEmpty() || stack.pop() != pairs.get(c)) return false;
        }
    }
    return stack.isEmpty();
}

This one also skips any other characters, so "(a + b) * [c]" works.

Quick early exit: a string with an odd length can never be valid. if (s.length() % 2 != 0) return false;

Cost: O(n) time, O(n) space in the worst case (all opening brackets).

24. Reverse a queue

Problem: a queue holds 1, 2, 3, 4, 5 with 1 at the front. Reverse it so 5 is at the front.

Plan: a queue gives elements back in the same order. A stack gives them back reversed. So pour the queue into a stack, then pour the stack back into the queue.

static void reverseQueue(Queue<Integer> queue) {
    Deque<Integer> stack = new ArrayDeque<>();
    while (!queue.isEmpty()) {
        stack.push(queue.poll());
    }
    while (!stack.isEmpty()) {
        queue.add(stack.pop());
    }
}
Queue<Integer> q = new ArrayDeque<>(List.of(1, 2, 3, 4, 5));
reverseQueue(q);
System.out.println(q);   // [5, 4, 3, 2, 1]

With recursion

“Can you do it without a stack?” is a common follow-up. Recursion uses the call stack instead: take the front element, reverse the rest, then put the element at the back.

static void reverseQueue(Queue<Integer> queue) {
    if (queue.isEmpty()) return;
    int front = queue.poll();
    reverseQueue(queue);
    queue.add(front);
}

It’s elegant, but each element is one level of recursion, so a very large queue can cause a StackOverflowError. Say that out loud; it shows you know the trade-off.

Cost: O(n) time and O(n) space for both versions.

25. Generate binary numbers from 1 to N

Problem: for N = 5, print the binary form of 1 to 5:

1
10
11
100
101

You could just call Integer.toBinaryString(i) in a loop. The interviewer knows that. This problem is about seeing a pattern that a queue can produce.

The pattern: every binary number makes two “children” by adding a 0 or a 1 at the end. 1 makes 10 and 11. 10 makes 100 and 101. If you visit them level by level, you get them in counting order. “Level by level” is what a queue does.

Five rounds of a queue. Round 1: the queue holds 1; it is printed. Round 2: the queue holds 10 and 11; 10 is printed. Round 3: 11, 100, 101; 11 is printed. Round 4: 100, 101, 110, 111; 100 is printed. Round 5: 101, 110, 111, 1000, 1001; 101 is printed. The front of the queue is yellow each time. A note says: poll the yellow front, print it, then add it with a 0 and with a 1 at the back.
Each round: take one from the front, add its two children at the back.

Plan: start with "1" in the queue. Then N times: take the front, print it, and add it with "0" and with "1" at the back.

static List<String> binaryNumbers(int n) {
    List<String> result = new ArrayList<>();
    Queue<String> queue = new ArrayDeque<>();
    queue.add("1");
    for (int i = 0; i < n; i++) {
        String current = queue.poll();
        result.add(current);
        queue.add(current + "0");
        queue.add(current + "1");
    }
    return result;
}
binaryNumbers(5).forEach(System.out::println);

This “take from the front, add the next ones at the back” loop is called breadth-first search (BFS). You’ll use the exact same shape for tree level-order traversal, shortest paths in a grid, and “rotting oranges” style problems. That’s the real reason this problem is on the list.

Cost: O(n) strings produced, each up to about log₂ n characters long.

What you practised

  • Stack (LIFO) vs queue (FIFO), and which problems need which
  • ArrayDeque as both, and why not the old Stack class
  • push / pop / peek and add / poll
  • The “push what you expect” trick for brackets
  • Recursion as a hidden stack
  • The BFS loop: poll one, add its children

Next: Phase 7, Java stream interview questions. You’ve solved everything with loops. Now the same problems get much shorter.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.