Open In App

Check for balanced parentheses in Python

Last Updated : 31 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

For a string that contains different types of parentheses such as (), {}, and []. We need to write a Python program to determine whether the parentheses are balanced. The parentheses are balanced if:

  1. Every opening parenthesis has a corresponding closing parenthesis of the same type.
  2. The pairs of parentheses are properly nested.

Using a Stack()

stack check balanced parentheses involves pushing opening brackets and popping them when encountering closing ones. If the stack is empty at the end, the parentheses are balanced. The stack naturally enforces last-in-first-out (LIFO) order, determining how parentheses must close in the correct sequence.

Example:

Python
s = "{[()()]}"
st = []  
for c in s:
  
  	 # Push opening brackets onto the stack
    if c in '({[': 
        st.append(c)
    
    # Check for matching closing bracket
    elif c in ')}]':  
        if not st or (c == ')' and st[-1] != '(') or (c == '}' and st[-1] != '{') or (c == ']' and st[-1] != '['):
            print(False)  # Mismatched bracket
            break
        st.pop()  # Pop matched opening bracket

else:
    print(True if not st else False)  # Balanced if stack is empty

Output
True

Explanation:

  • The code initializes an empty list st to use as a stack for tracking opening brackets.
  • It loops through each character in the string s. For opening brackets ((, {, [), it pushes them onto the stack. For closing brackets (), }, ]), it checks if the stack is not empty and the top of the stack is the corresponding opening bracket.
  • If a closing bracket does not match the top opening bracket or the stack is empty, it prints False and stops the loop.
  • After the loop, it prints True if the stack is empty (all brackets are balanced) or False if there are unmatched opening brackets remaining in the stack.

Let's explore other methods to achieve the same:

Using a Counter

A counter tracks opening and closing parentheses. The parentheses are balanced if the counter equals zero at the end. Simply matching counts can’t detect improper nesting like ([)] (where overall counts match, but they are not in the correct order).

Example:

Python
counter = 0
s = "{[()()]}" 
for ch in s:
  
  	# Increment counter for opening parenthesis
    if ch == '(':  
        counter += 1
        
    # Decrement counter for closing parenthesis
    elif ch == ')':  
        counter -= 1
    
    # If counter goes negative, parentheses are unbalanced
    if counter < 0:  
        print("Unbalanced")
        break
if counter == 0:
    print("Balanced")
else:
    print("Unbalanced")

Output
Balanced

Explanation:

  • It loops through each character in the string s. When it encounters an opening parenthesis '(', it increments the counter by 1. When it encounters a closing parenthesis ')', it decrements the counter by 1.
  • If at any point the counter goes negative (i.e., a closing parenthesis appears without a matching opening one), it prints "Unbalanced" and exits the loop. After checking all characters, if the counter is 0, it means all opening parentheses had matching closing ones, so it prints "Balanced".

Using Regular Expression

Regular Expression can match balanced parentheses by repeatedly matching pairs of parentheses until no more can be removed.

Example:

Python
import re  # Import regex module
s = "(())()"  # Input string

# Remove pairs of '()' until no more are found
while re.search(r'\(\)', s):  
    s = re.sub(r'\(\)', '', s)

# If the string is empty, the parentheses are balanced
print("Balanced" if not s else "Unbalanced")

Output
Balanced

Explanation:

  • The while loop uses re.search(r'\(\)', s) to check if there are any pairs of parentheses () in the string. If a pair is found, re.sub(r'\(\)', '', s) removes it from the string. The loop continues until no more pairs of '()' are found.
  • It checks if the string is empty afterward, printing "Balanced" if so, otherwise "Unbalanced."

Next Article

Similar Reads