Balanced brackets
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Checking for balanced brackets is a fundamental computer science problem. A stack tracks opening brackets so closing brackets can be matched in correct nested order.
Matching bracket pairs with a stack
A string has balanced brackets when every opening bracket is closed by the same type of bracket, in the correct nested order.
Compilers and editors must check that each closing bracket matches the most recent unclosed opener. A stack keeps the openers in exactly that order.
- Scan string characters from left to right.
- Push opening brackets onto an ArrayDeque stack.
- When reading a closing bracket, verify the stack is not empty.
- Pop the top character and check if it matches the current closer.
Push and pop on {[()]}
Step 1 of 8
Example 1 · Brute force: delete matching pairs again and again (O(n^2) time, O(n) extra space)
public class BracketsReplaceDemo { static boolean isBalanced(String s) { int before; do { before = s.length(); s = s.replace("()", "").replace("[]", "").replace("{}", ""); } while (s.length() != before); return s.isEmpty(); }
public static void main(String[] args) { System.out.println("{[()]}: " + isBalanced("{[()]}")); System.out.println("([)]: " + isBalanced("([)]")); System.out.println("((: " + isBalanced("((")); }}{[()]}: true
([)]: false
((: falseWhat this code does
- Each round removes the innermost pairs, so
{[()]}shrinks to{[]}, then{}, then an empty string. - Every
replacebuilds a new string and a deeply nested input needs about n / 2 rounds, so total work is O(n^2). - A stack reads the string once, as shown next.
Example 2 · Optimal: one pass with a stack (O(n) time, O(n) space)
import java.util.ArrayDeque;import java.util.Deque;
public class BalancedBracketsDemo { public static boolean isValid(String s) { if (s.length() % 2 != 0) return false; Deque<Character> stack = new ArrayDeque<>();
for (char ch : s.toCharArray()) { if (ch == '(' || ch == '{' || ch == '[') { stack.push(ch); } else { if (stack.isEmpty()) return false; char open = stack.pop(); if (ch == ')' && open != '(') return false; if (ch == '}' && open != '{') return false; if (ch == ']' && open != '[') return false; } } return stack.isEmpty(); }
public static void main(String[] args) { System.out.println("()[]{}: " + isValid("()[]{}")); System.out.println("([)]: " + isValid("([)]")); System.out.println("{[]}: " + isValid("{[]}")); }}()[]{}: true
([)]: false
{[]}: trueWhat this code does
([)]fails because[must close before)closes.- Odd length strings are rejected immediately in O(1) time.
- Valid expressions leave the stack completely empty.
Example 3 · Clean Lookup Pattern Using Switch
import java.util.ArrayDeque;import java.util.Deque;
public class CleanBracketSwitchDemo { public static boolean isBalanced(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(); }
public static void main(String[] args) { System.out.println("((())): " + isBalanced("((()))")); System.out.println("()) : " + isBalanced("())")); }}((())): true ()) : false
What this code does
- Pushing expected closing characters simplifies comparisons.
- When a closer arrives, it directly matches
stack.pop(). - This approach removes nested if conditions.
Deleting matching pairs again and again rebuilds the string on every pass and takes O(n²) time (the first example). The stack reads the string once in O(n). When a closing bracket arrives, it must match the top of the stack.
Edge cases: a closing bracket on an empty stack (for example )) is invalid, and so are openers left on the stack at the end (for example (). Check isEmpty() before popping and again after the loop.
- Opening brackets
(,{,[: push onto the stack. - Closing brackets
),},]: pop and verify matching type. - Empty stack on close: invalid because there is no matching opener.
- Clean exit: stack must be empty after scanning all characters.
Exiting early and handling edge cases
Early exits return false as soon as the answer is certain, without scanning the rest of the string. If the string has an odd length, it cannot possibly be balanced. You can return false immediately.
if (s.length() % 2 != 0) return false; // odd length can never balancefor (char ch : s.toCharArray()) { if (ch == '(' || ch == '[' || ch == '{') { stack.push(ch); } else { if (stack.isEmpty()) return false; // closing bracket with nothing open char open = stack.pop(); if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{')) return false; // first mismatch: stop here }}return stack.isEmpty(); // leftover openers such as "((("If a closing bracket arrives while the stack is empty, return false on that step. There is no need to examine the rest of the string.
Finally, check stack.isEmpty() at the end. Strings with leftover openers like ((( fail this final check.
- Odd string length: return
falseimmediately. - Closing bracket on empty stack: return
falsewithout continuing. - Mismatch detected: exit immediately on first mismatch.
- Leftover openers: return
stack.isEmpty()to catch trailing unclosed brackets.
Find the bug
Find the bug in the bracket checker
Select the line that is wrong.
This should return false for a string that starts with ")".
Round 1 of 3stack.isEmpty() before popping to avoid throwing NoSuchElementException on stray closing brackets.Real-world syntax parsing and linting
Code editors use bracket matching algorithms to highlight paired braces. When you type a closing brace, the editor matches it with the correct opening line.
Example 4 · Validating Tag Nesting with a Stack
import java.util.ArrayDeque;import java.util.Deque;
public class TagNestingDemo { public static boolean validateTags(String[] tags) { Deque<String> stack = new ArrayDeque<>(); for (String tag : tags) { if (!tag.startsWith("/")) { stack.push(tag); } else { String expected = tag.substring(1); if (stack.isEmpty() || !stack.pop().equals(expected)) { return false; } } } return stack.isEmpty(); }
public static void main(String[] args) { String[] valid = {"div", "p", "/p", "/div"}; String[] invalid = {"div", "p", "/div", "/p"}; System.out.println("Valid tags: " + validateTags(valid)); System.out.println("Invalid tags: " + validateTags(invalid)); }}Valid tags: true Invalid tags: false
What this code does
- Opening tags are pushed onto the stack.
- Closing tags must match the most recently opened tag.
- Tag validation mirrors bracket matching.
Compilers and linters parse expressions into abstract syntax trees using stack validation. JSON parsers verify matching curly braces and square brackets in data streams. HTML and XML document parsers apply the exact same logic to opening and closing tags.
Where it is used:
- IDE editors: highlight matching bracket pairs in real time.
- Compilers: detect syntax errors and malformed expressions.
- Markup parsers: validate matching opening and closing tags.
Next step
Check your understanding
10 quick questions