Program to check whether different brackets are balanced and well-formed or not in Python

Checking whether brackets are balanced is a classic programming problem. A string of brackets is considered balanced when every opening bracket has a corresponding closing bracket in the correct order.

For example, the string "([()()]{[]})()" is balanced because each opening bracket matches with its corresponding closing bracket properly.

Algorithm Approach

We use a stack data structure to solve this problem efficiently ?

  • Create an empty stack to store opening brackets
  • Create a dictionary mapping each closing bracket to its opening counterpart
  • For each character in the string:
    • If it's a closing bracket, check if the stack top matches
    • If it's an opening bracket, push it onto the stack
  • The string is balanced if the stack is empty at the end

Implementation

class Solution:
    def solve(self, s):
        stack = []
        # Map closing brackets to their opening counterparts
        bracket_map = {'}': '{', ')': '(', ']': '['}
        
        for char in s:
            if char in '}])':  # Closing bracket
                if not stack or stack[-1] != bracket_map[char]:
                    return False
                stack.pop()
            else:  # Opening bracket
                stack.append(char)
        
        return not stack  # True if stack is empty

# Test the solution
solution = Solution()
test_string = "([()()]{[]})()"
result = solution.solve(test_string)
print(f"Is '{test_string}' balanced? {result}")
Is '([()()]{[]})()' balanced? True

Step-by-Step Execution

Let's trace through the example "([()()]{[]})()" ?

def detailed_check(s):
    stack = []
    bracket_map = {'}': '{', ')': '(', ']': '['}
    
    for i, char in enumerate(s):
        print(f"Step {i+1}: Processing '{char}', Stack: {stack}")
        
        if char in '}])':
            if not stack or stack[-1] != bracket_map[char]:
                return False
            stack.pop()
        else:
            stack.append(char)
    
    print(f"Final stack: {stack}")
    return len(stack) == 0

# Trace the example
result = detailed_check("([()])")
print(f"Balanced: {result}")
Step 1: Processing '(', Stack: []
Step 2: Processing '[', Stack: ['(']
Step 3: Processing '(', Stack: ['(', '[']
Step 4: Processing ')', Stack: ['(', '[', '(']
Step 5: Processing ']', Stack: ['(', '[']
Step 6: Processing ')', Stack: ['(']
Final stack: []
Balanced: True

Testing Different Cases

def is_balanced(s):
    stack = []
    bracket_map = {'}': '{', ')': '(', ']': '['}
    
    for char in s:
        if char in '}])':
            if not stack or stack[-1] != bracket_map[char]:
                return False
            stack.pop()
        else:
            stack.append(char)
    
    return len(stack) == 0

# Test various cases
test_cases = [
    "([()()]{[]})()",  # Balanced
    "([)]",            # Not balanced - wrong order
    "(((",             # Not balanced - unmatched opening
    ")))",             # Not balanced - unmatched closing
    "",                # Balanced - empty string
    "{[()]}"           # Balanced - nested properly
]

for test in test_cases:
    result = is_balanced(test)
    print(f"'{test}' ? {result}")
'([()()]{[]})()' ? True
'([)]' ? False
'(((' ? False
')))' ? False
'' ? True
'{[()]}' ? True

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(n) in the worst case when all characters are opening brackets

Conclusion

The stack-based approach efficiently checks bracket balance by matching closing brackets with their most recent unmatched opening bracket. This solution works for any combination of round, square, and curly brackets.

Updated on: 2026-03-25T10:49:04+05:30

334 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements