Check for balanced parentheses in Python

In this article, we will solve the problem of checking balanced parentheses. A string has balanced parentheses when every opening bracket has a corresponding closing bracket in the correct order.

The following are the conditions for balanced parentheses −

  • Every opening parenthesis has a corresponding closing parentheses.
  • Parentheses should be closed in the correct order.

For example, "{[()]}" is a balanced parenthesis. Consider the same example with different arrangement "{([})]" which is unbalanced parentheses.

Using List and For Loop

The stack-based approach uses a list to track opening brackets and matches them with corresponding closing brackets.

Algorithm

Following are the steps to check whether the parentheses are balanced or not using the list and for loop −

  • Create one list for open parentheses and another list for closed parentheses.
  • Create an empty stack to track the open parentheses and iterate through the given string using a for loop.
  • If the iterated value is present in the open list, append it to the stack.
  • If the iterated value is present in the closed list, find its index value in the closed list.
  • If the stack is not empty, check if the corresponding opening bracket matches the top of stack, then pop the stack otherwise return Unbalanced.
  • After the loop, if the stack is empty, return "Balanced".
  • If the stack is not empty, return "Unbalanced".

Example

Following is an example to check whether parentheses are balanced or not using a list and for loop −

open_brackets = ["[", "{", "("]
close_brackets = ["]", "}", ")"]

def check_balanced(myStr):
    stack = []
    for char in myStr:
        if char in open_brackets:
            stack.append(char)
        elif char in close_brackets:
            pos = close_brackets.index(char)
            if ((len(stack) > 0) and
                (open_brackets[pos] == stack[len(stack)-1])):
                stack.pop()
            else:
                return "Unbalanced"
    if len(stack) == 0:
        return "Balanced"
    else:
        return "Unbalanced"
 
my_str1 = "{[]{()}}"
print(my_str1, "-", check_balanced(my_str1))
my_str2 = "{([}])]"
print(my_str2, "-", check_balanced(my_str2))

Following is the output of the above code −

{[]{()}} - Balanced
{([}])] - Unbalanced

Using Dictionary

A more elegant approach uses a dictionary to map opening brackets to their corresponding closing brackets ?

Algorithm

Following are the steps to check whether parentheses are balanced or not using a dictionary

  • Create a dictionary that maps opening brackets to closing brackets.
  • Create an empty stack to track opening brackets.
  • Iterate through each character in the string.
  • If the character is an opening bracket, push its corresponding closing bracket onto the stack.
  • If the character is a closing bracket, check if it matches the top of stack. If not, return "Unbalanced".
  • After the loop, return "Balanced" if stack is empty, otherwise "Unbalanced".

Example

Following is an example to check whether parentheses are balanced or not using a dictionary

def check_balanced(expression):
    open_brackets = tuple('({[')
    close_brackets = tuple(')}]')
    bracket_map = dict(zip(open_brackets, close_brackets))
    stack = []
    
    for char in expression:
        if char in open_brackets:
            stack.append(bracket_map[char])
        elif char in close_brackets:
            if not stack or char != stack.pop():
                return "Unbalanced"
    
    return "Balanced" if not stack else "Unbalanced"

my_str1 = "{[]{()}}"
print(my_str1, "-", check_balanced(my_str1))
my_str2 = "((()"
print(my_str2, "-", check_balanced(my_str2))

Following is the output of the above code −

{[]{()}} - Balanced
((() - Unbalanced

Comparison

Method Time Complexity Best For
List Approach O(n) Simple implementation
Dictionary Approach O(n) More readable and elegant

Conclusion

Both approaches use a stack data structure to solve the balanced parentheses problem efficiently. The dictionary approach is more elegant and readable, while the list approach is simpler to understand for beginners.

Updated on: 2026-03-25T06:38:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements