Python Program to Check Balanced Parentheses
You can check balanced parentheses in Python by using a stack: push '(' when found, pop when ')' is found, and ensure the stack is empty at the end, like
def is_balanced(s): stack = []; for char in s: if char == '(' : stack.append(char); elif char == ')': if not stack: return False; stack.pop(); return not stack.Examples
Input"()()"
OutputTrue
Input"(()())"
OutputTrue
Input"(()"
OutputFalse
How to Think About It
To check if parentheses are balanced, imagine reading the string from left to right. Every time you see an opening parenthesis '(', you remember it by putting it on a stack. When you see a closing parenthesis ')', you remove the last opening one you remembered. If at the end you have no leftover openings, the parentheses are balanced.
Algorithm
1
Create an empty stack.2
Go through each character in the string.3
If the character is '(', push it onto the stack.4
If the character is ')', check if the stack is empty; if yes, return False because there's no matching '('.5
If the stack is not empty, pop the top element.6
After checking all characters, if the stack is empty, return True; otherwise, return False.Code
python
def is_balanced(s): stack = [] for char in s: if char == '(': stack.append(char) elif char == ')': if not stack: return False stack.pop() return not stack print(is_balanced('()()')) # True print(is_balanced('(()())')) # True print(is_balanced('(()')) # False
Output
True
True
False
Dry Run
Let's trace the string '(()' through the code
1
Start with empty stack
stack = []
2
Read '('
stack = ['(']
3
Read '('
stack = ['(', '(']
4
Read ')'
stack before pop = ['(', '('], after pop = ['(']
5
End of string
stack = ['('], not empty, so return False
| Character | Stack Before | Stack After | Action |
|---|---|---|---|
| ( | [] | ( | Push '(' |
| ( | ( | (,( | Push '(' |
| ) | (,( | ( | Pop '(' |
Why This Works
Step 1: Use a stack to track '('
Each '(' is saved on the stack to remember it needs a matching ')'.
Step 2: Match ')' with last '('
When ')' appears, it must match the most recent '(' on the stack, so we pop it.
Step 3: Check stack emptiness at end
If the stack is empty after processing all characters, all parentheses matched correctly.
Alternative Approaches
Using a counter
python
def is_balanced_counter(s): count = 0 for char in s: if char == '(': count += 1 elif char == ')': count -= 1 if count < 0: return False return count == 0 print(is_balanced_counter('()()')) # True print(is_balanced_counter('(()())')) # True print(is_balanced_counter('(()')) # False
This method uses a simple counter instead of a stack, which is faster and uses less memory but only works for one type of bracket.
Using recursion
python
def is_balanced_recursive(s, index=0, count=0): if count < 0: return False if index == len(s): return count == 0 if s[index] == '(': count += 1 elif s[index] == ')': count -= 1 return is_balanced_recursive(s, index + 1, count) print(is_balanced_recursive('()()')) # True print(is_balanced_recursive('(()())')) # True print(is_balanced_recursive('(()')) # False
Recursion can solve the problem elegantly but may hit limits on very long strings.
Complexity: O(n) time, O(n) space
Time Complexity
The program checks each character once, so time grows linearly with input size.
Space Complexity
The stack can hold up to all opening parentheses, so space grows linearly in the worst case.
Which Approach is Fastest?
The counter method is fastest and uses less memory but only works for simple parentheses, while the stack method is more general.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Stack | O(n) | O(n) | All types of parentheses and nested structures |
| Counter | O(n) | O(1) | Simple parentheses only |
| Recursion | O(n) | O(n) | Elegant code but limited by recursion depth |
Use a stack or a counter to track opening parentheses and ensure every closing one matches.
Forgetting to check if the stack is empty before popping causes errors on unbalanced strings.