Java String Program · S34
Check Balanced Parentheses in Java
Every opening bracket must be closed by the same type of bracket, in the reverse order it was opened. A stack remembers what still needs to be closed.
Problem Statement
Write a method that returns true if the brackets (), [] and {} in a string are balanced: every opening bracket has a matching closing bracket of the same type, and pairs are properly nested.
All other characters are ignored, so the method can check a line of code. A string with no brackets is balanced.
Input/Output Examples
"if (a[i] > {b}.c)"OutputtrueExplanation: the brackets ( [ ] { } ) are properly nested."([)]"OutputfalseExplanation: ] arrives while ( is the most recent unclosed bracket."((" and ")("OutputfalseExplanation: the first leaves brackets open; the second closes before anything is open.Visual Explanation
- Read (stack)push the expected )
- Read [stack)]push the expected ]
- Read ]stack)pop ] = ] match
- Read { }stack)push }, then pop it match
- Read )pop ) = ), stack emptytrue
"if (a[i] > {b}.c)": each opening bracket pushes the closing bracket it expects (purple); each closing bracket must equal the top of the stack.Pushing the expected closer rather than the opener makes the check a single comparison. At the end, the stack must be empty; otherwise some bracket was never closed.
Approaches
The stack approach is the standard answer. The pair-removal approach is shorter to describe but much slower.
Approach 1: Stack of Expected Closers (Recommended)
Idea: push the matching closer for each opening bracket, and pop and compare for each closing bracket.
- For
(,[or{, push),]or}. - For a closer, return
falseif the stack is empty or the popped value differs. - Ignore every other character.
- Return
trueonly if the stack is empty at the end.
Time: O(n) · Space: O(n).
Approach 2: Remove Matching Pairs
Idea: keep only the brackets, then repeatedly delete adjacent pairs (), [] and {} until nothing changes.
- Remove every character that is not a bracket.
- Delete all adjacent matching pairs.
- Repeat while the string keeps getting shorter; it is balanced if it ends empty.
Time: O(n²) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Stack of Expected Closers (Recommended)
Uses ArrayDeque as the stack and a switch with arrow labels (Java 14+).
import java.util.ArrayDeque;
import java.util.Deque;
public class BracketsStack {
// Pushes the closer we expect; every closer must match the most recent expectation
static boolean isBalanced(String text) {
Deque<Character> expected = new ArrayDeque<>();
for (char c : text.toCharArray()) {
switch (c) {
case '(' -> expected.push(')');
case '[' -> expected.push(']');
case '{' -> expected.push('}');
case ')', ']', '}' -> {
if (expected.isEmpty() || expected.pop() != c) {
return false; // wrong closer, or nothing open
}
}
default -> { } // other characters are ignored
}
}
return expected.isEmpty(); // nothing may stay open
}
public static void main(String[] args) {
String[] inputs = {"if (a[i] > {b}.c)", "([)]", "((", ")("};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + isBalanced(s));
}
}
}
"if (a[i] > {b}.c)" -> true
"([)]" -> false
"((" -> false
")(" -> false
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Remove Matching Pairs
Each round removes at least one pair, so there can be up to n / 2 rounds over the string.
public class BracketsRemovePairs {
// Keeps only brackets, then deletes adjacent pairs until nothing changes
static boolean isBalanced(String text) {
String s = text.replaceAll("[^()\\[\\]{}]", "");
while (true) {
String next = s.replace("()", "").replace("[]", "").replace("{}", "");
if (next.equals(s)) {
return s.isEmpty();
}
s = next;
}
}
public static void main(String[] args) {
String[] inputs = {"if (a[i] > {b}.c)", "([)]", "((", ")("};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + isBalanced(s));
}
}
}
"if (a[i] > {b}.c)" -> true
"([)]" -> false
"((" -> false
")(" -> false
Time complexity: O(n²) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Stack of Expected Closers | O(n) | O(n) |
| Remove Matching Pairs | O(n²) | O(n) |
Here n is the length of the string. The stack version reads each character once and stores at most n brackets; the removal version may rebuild the string many times.
Interview Tips and Recommended Approach
- Check the empty stack before popping. A closer with nothing open, as in
")(", must returnfalse, not throw. - Check the stack at the end.
"(("never fails a comparison, but it is still unbalanced. - Explain why counters fail. Counting opens and closes works for one bracket type but accepts
"([)]"with several types. - Prefer
ArrayDequetoStack. The legacyStackclass is synchronized and slower.
Recommended Approach: Stack of Expected Closers
Why: it checks the string in one pass, handles any mix of bracket types and nesting depth, and its logic is easy to justify.