0
0
JavaProgramBeginner · 2 min read

Java Program to Check Balanced Parentheses

Use a stack in Java to check balanced parentheses by pushing opening brackets with stack.push() and popping when a matching closing bracket appears, returning true if all match and stack is empty at the end.
📋

Examples

Input()[]{}
OutputBalanced
Input([)]
OutputNot Balanced
Input
OutputBalanced
🧠

How to Think About It

To check balanced parentheses, think of matching each opening bracket with its correct closing bracket in order. Use a stack to remember opening brackets as you see them. When you find a closing bracket, check if it matches the last opening bracket you saved. If it does, remove that opening bracket from the stack. If not, the parentheses are not balanced. At the end, if nothing is left in the stack, all parentheses matched correctly.
📐

Algorithm

1
Create an empty stack to hold opening brackets.
2
Go through each character in the input string.
3
If the character is an opening bracket, push it onto the stack.
4
If the character is a closing bracket, check if the stack is empty or the top does not match the closing bracket; if so, return not balanced.
5
If it matches, pop the top of the stack.
6
After processing all characters, if the stack is empty, return balanced; otherwise, not balanced.
💻

Code

java
import java.util.Stack;

public class BalancedParentheses {
    public static boolean isBalanced(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else if (c == ')' || c == '}' || c == ']') {
                if (stack.isEmpty()) return false;
                char top = stack.pop();
                if ((c == ')' && top != '(') ||
                    (c == '}' && top != '{') ||
                    (c == ']' && top != '[')) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        String input = "()[]{}";
        System.out.println(isBalanced(input) ? "Balanced" : "Not Balanced");
    }
}
Output
Balanced
🔍

Dry Run

Let's trace the input "()[]{}" through the code

1

Start with empty stack

stack = []

2

Read '(' - opening bracket

stack = ['(']

3

Read ')' - closing bracket matches '('

stack after pop = []

4

Read '[' - opening bracket

stack = ['[']

5

Read ']' - closing bracket matches '['

stack after pop = []

6

Read '{' - opening bracket

stack = ['{']

7

Read '}' - closing bracket matches '{'

stack after pop = []

8

End of string, stack empty

stack = [] means Balanced

CharacterStack Content
(['(']
)[]
[['[']
][]
{['{']
}[]
💡

Why This Works

Step 1: Use a stack to track opening brackets

A stack remembers the order of opening brackets so we can match them later with closing brackets.

Step 2: Match closing brackets with last opening bracket

When a closing bracket appears, it must match the last opening bracket on the stack to be balanced.

Step 3: Check stack emptiness at the end

If the stack is empty after processing all characters, all brackets matched correctly, so the string is balanced.

🔄

Alternative Approaches

Using counters for only parentheses
java
public static boolean isBalancedSimple(String s) {
    int count = 0;
    for (char c : s.toCharArray()) {
        if (c == '(') count++;
        else if (c == ')') {
            if (count == 0) return false;
            count--;
        }
    }
    return count == 0;
}
This works only for parentheses '()' and is simpler but cannot handle mixed types like '{}', '[]'.
Using recursion to check pairs
java
public static boolean isBalancedRecursive(String s) {
    if (s.isEmpty()) return true;
    int len = s.length();
    for (int i = 0; i < len - 1; i++) {
        if ((s.charAt(i) == '(' && s.charAt(i+1) == ')') ||
            (s.charAt(i) == '{' && s.charAt(i+1) == '}') ||
            (s.charAt(i) == '[' && s.charAt(i+1) == ']')) {
            return isBalancedRecursive(s.substring(0, i) + s.substring(i+2));
        }
    }
    return false;
}
This recursive method removes pairs step-by-step but is less efficient and harder to read.

Complexity: O(n) time, O(n) space

Time Complexity

The program checks each character once, so it runs in linear time relative to the input length.

Space Complexity

The stack can hold up to all opening brackets, so in the worst case, space grows linearly with input size.

Which Approach is Fastest?

The stack approach is efficient and clear for all bracket types; simple counters are faster but limited to one bracket type.

ApproachTimeSpaceBest For
Stack methodO(n)O(n)All bracket types, mixed input
Counter methodO(n)O(1)Only parentheses '()'
Recursive methodO(n^2)O(n)Small inputs, educational purposes
💡
Use a stack to track opening brackets and match them with closing ones for balanced parentheses.
⚠️
Forgetting to check if the stack is empty before popping causes errors when closing brackets appear first.