Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to check whether parentheses are balanced or not in Python
Checking whether parentheses are balanced is a fundamental programming problem. A string has balanced parentheses if every opening parenthesis ( has a corresponding closing parenthesis ) and they appear in the correct order.
So, if the input is like s = "(()())(())", then the output will be True because all parentheses are properly matched.
Algorithm Approach
To solve this problem, we will follow these steps ?
- Initialize a counter
open_countto track open parentheses - For each character in the string:
- If it's
'(', increment the counter - If it's
')', decrement the counter - If counter becomes negative, return
False(more closing than opening)
- If it's
- Return
Trueif counter equals zero (all parentheses matched)
Example
def is_balanced(s):
open_count = 0
for char in s:
if char == '(':
open_count += 1
elif char == ')':
open_count -= 1
# More closing parentheses than opening
if open_count < 0:
return False
# All parentheses matched if count is zero
return open_count == 0
# Test cases
test_strings = ["(()())(())", "(()", "())", "()()", ""]
for s in test_strings:
result = is_balanced(s)
print(f"'{s}' is balanced: {result}")
'(()())(())' is balanced: True '(()' is balanced: False '())' is balanced: False '()()' is balanced: True '' is balanced: True
Using Stack Approach
An alternative approach uses a stack data structure to track opening parentheses ?
def is_balanced_stack(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False # No matching opening parenthesis
stack.pop()
return len(stack) == 0 # Stack should be empty
# Test the stack approach
test_string = "(()())(())"
result = is_balanced_stack(test_string)
print(f"'{test_string}' is balanced: {result}")
'(()())(())' is balanced: True
Comparison
| Approach | Space Complexity | Time Complexity | Best For |
|---|---|---|---|
| Counter Method | O(1) | O(n) | Simple parentheses only |
| Stack Method | O(n) | O(n) | Multiple bracket types |
Conclusion
The counter method is more efficient for simple parentheses checking with O(1) space complexity. Use the stack approach when dealing with multiple types of brackets like [], {}, and ().
Advertisements
