Program to Check Balanced of Parenthesis in Python

Check the balance of parenthesis in Python

To check balanced parenthesis is a basic interview question where we are asked to find whether the given string(of brackets) is balanced or not. To do this , the traditional way of doing is using stacks but we can also find by using normal programming techniques. Different brackets are  ( ) , [ ] , { }. Question can be asked on any type of bracket or of all types of brackets.

Program to check the balance of parenthesis in Python
Balanced Parenthesis Problem Python

Missing Braces Program in Python Working:

  • Step 1: Take the input string
  • Step 2: Call the isbalanced function
  • Step 3: This function returns True if the string is balanced, else False
  • Step 4: This function returns true or false for the string that contains ( )

Python code:- Check the balance of parenthesis in Python

Run
def isbalanced(s):
  c= 0
  ans=False
  for i in s:
    if i == "(": 
     c += 1
    elif i == ")":
     c-= 1
    if c < 0:
     return ans
    if c==0:
     return not ans
  return ans
s="{[]}"
print("Given string is balanced :",isbalanced(s))
Given string is balanced : True

Working:

This approach is to check whether the string is balanced or not in case the string contains several types of brackets like { ( [ ] ) }

  • Step 1: Take the input string
  • Step 2: Call the isbalanced function
  • Step 3: This function returns True if string is balanced , else False
  • Step 4: This function replaces the set of brackets until the string len becomes zero

Solution 2:

Run
def isbalanced(s):
    while(len(s)!=0):
        s=s.replace('()','')
        s=s.replace('[]','')
        s=s.replace('{}','')
    if(len(s)==0):
        return True
    else:
        return False
s=input("Enter a string of brackets:")
print("Given string is balanced:",isbalanced(s))
Enter a string of brackets: ({{}}){}[]
Given string is balanced : True
meme on balanced paranthesis

6 comments on “Program to Check Balanced of Parenthesis in Python”


  • ddoddi

    class Solution:
    def isValid(self, s: str) -> bool:
    for i in range(len(s)//2+1):
    s=s.replace(“()”,””)
    s=s.replace(“{}”,””)
    s=s.replace(“[]”,””)

    if len(s)==0:
    return True
    else:
    return False


  • abhishek

    def is_balanced_parentheses(s):
    stack = [] # Create an empty stack to store opening brackets
    opening_brackets = ‘([{‘
    closing_brackets = ‘)]}’

    for char in s: # Loop through each character in the input string
    if char in opening_brackets: # Check if the character is an opening bracket
    stack.append(char) # Push the opening bracket onto the stack
    elif char in closing_brackets: # Check if the character is a closing bracket
    if not stack: # If the stack is empty, no matching opening bracket exists
    return False
    if opening_brackets.index(stack.pop()) != closing_brackets.index(char):
    return False # If the opening bracket on top of the stack doesn’t match the closing bracket, return False

    return len(stack) == 0 # After processing all characters, if the stack is empty, the brackets are balanced

    # Test cases
    test_strings = [
    “()”, # Balanced
    “([])”, # Balanced
    “{[()]}”, # Balanced
    “{[()]”, # Not balanced
    “({})”, # Balanced
    “((())())”, # Balanced
    “())(“, # Not balanced
    ]

    for test_string in test_strings:
    if is_balanced_parentheses(test_string):
    print(f”‘{test_string}’ is balanced.”)
    else:
    print(f”‘{test_string}’ is not balanced.”)


  • mayurpatil25027

    Both of the code give false Output

    Code 1 will return wrong output for string: “{ ] [ }”
    and code 2 is showing and infinite loop


  • nitesh

    a=”[](}”
    c=0
    for i in a:
    if i==”(“:
    c+=1
    elif i==”)”:
    c-=1
    elif i==”[“:
    c+=2
    elif i==”]”:
    c-=2
    elif i==”{“:
    c+=3
    elif i==”}”:
    c-=3
    if c==0:
    print(a,”Balanced”)
    else:
    print(a,”Not balanced”)