Open In App

Python Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack

Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.

Example



Input: exp = “[()]{}{[()()]()}” 
Output: Balanced

Input: exp = “[(])” 
Output: Not Balanced 



Algorithm: 

Below image is a dry run of the above approach:

Below is the implementation of the above approach:




# Python3 program to check for
# balanced brackets.
  
# function to check if
# brackets are balanced
  
  
def areBracketsBalanced(expr):
    stack = []
  
    # Traversing the Expression
    for char in expr:
        if char in ["(", "{", "["]:
  
            # Push the element in the stack
            stack.append(char)
        else:
  
            # IF current character is not opening
            # bracket, then it must be closing.
            # So stack cannot be empty at this point.
            if not stack:
                return False
            current_char = stack.pop()
            if current_char == '(':
                if char != ")":
                    return False
            if current_char == '{':
                if char != "}":
                    return False
            if current_char == '[':
                if char != "]":
                    return False
  
    # Check Empty Stack
    if stack:
        return False
    return True
  
  
# Driver Code
if __name__ == "__main__":
    expr = "{()}[]"
  
    # Function call
    if areBracketsBalanced(expr):
        print("Balanced")
    else:
        print("Not Balanced")
  
# This code is contributed by AnkitRai01 and improved
# by Raju Pitta

Output
Balanced

Time Complexity: O(n) 
Auxiliary Space: O(n) for stack. 

Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details!


Article Tags :