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:
- A closing bracket with nothing open, like
")": the stack is empty, sostack.isEmpty()returnsfalsebefore we try to pop. - The wrong closing bracket, like
"(]": we pop)but see]. - Brackets left open, like
"(": the loop ends with something still on the stack, soreturn stack.isEmpty()givesfalse.
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.
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
ArrayDequeas both, and why not the oldStackclasspush/pop/peekandadd/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