Stacks and Queues
Balanced Parentheses
Walk a string of bracket characters. Push every opening bracket. On a closing bracket, pop and verify it matches; mismatch or empty-stack pop means unbalanced. At end of string, stack must be empty.
Algorithm
Canonical input "({[]})" (balanced) finishes with the stack empty and
the result true.
Basic Implementation
Basic.java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
public class Basic {
public static void main(String[] args) {
String text = "({[]})";
Map<Character, Character> pairs = new HashMap<>();
pairs.put(')', '(');
pairs.put(']', '[');
pairs.put('}', '{');
Deque<Character> stack = new ArrayDeque<>();
boolean balanced = true;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
balanced = false;
break;
}
stack.pop();
}
}
if (!stack.isEmpty()) {
balanced = false;
}
System.out.println(balanced);
}
}
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- Java:
ArrayDeque<Character>is the idiomatic stack; avoidjava.util.Stack, which is synchronized and legacy. - The replay highlights the current character, shows the stack updating each frame, and surfaces the final balanced/unbalanced verdict.
stack push/pop
Use an `ArrayDeque<Character>` as the stack.
matching map
A small `HashMap` mapping each closing bracket to its expected opener keeps the lesson compact.