Validate balanced brackets.
Problem
Given a string of ()[]{}, decide whether every bracket is closed by the same type in the correct order: "([]{})" is valid, "([)]" is not.
Approach
Use a stack (ArrayDeque, not the legacy Stack). Push opening brackets; on a closing bracket, the top must be its matching opener. At the end the stack must be empty.
java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
class ValidBrackets {
private static final Map<Character, Character> PAIRS = Map.of(')', '(', ']', '[', '}', '{');
static boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if (PAIRS.containsKey(c)) {
if (stack.isEmpty() || stack.pop() != PAIRS.get(c)) return false;
}
// other characters are ignored
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(isValid("([]{})")); // true
System.out.println(isValid("([)]")); // false
System.out.println(isValid("((")); // false
}
}Complexity
O(n) time, O(n) space in the worst case.
Follow-up questions interviewers ask
Try answering each one before you open it.
What if there is only one bracket type?
You do not need a stack: keep a counter, increment on ( and decrement on ), return false if it ever goes negative, and check it is zero at the end. O(1) space.
Where does this pattern appear in real systems?
Parsers and expression evaluators (the shunting-yard algorithm uses an operator stack), validating nested structures such as JSON or XML, undo stacks, and matching begin/end markers in logs or traces.