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:
- Declare a character stack S.
- Now traverse the expression string exp.
- If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
- If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced.
- After complete traversal, if there is some starting bracket left in stack then “not balanced”
Below image is a dry run of the above approach:

Below is the implementation of the above approach:
Python3
def areBracketsBalanced(expr):
stack = []
for char in expr:
if char in [ "(" , "{" , "[" ]:
stack.append(char)
else :
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
if stack:
return False
return True
if __name__ = = "__main__" :
expr = "{()}[]"
if areBracketsBalanced(expr):
print ( "Balanced" )
else :
print ( "Not 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!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
19 May, 2022
Like Article
Save Article