Check if given expression is balanced expression or not

Given an string containing opening and closing braces, check if it represents a balanced expression or not.


For example,

{[{}{}]}[()], {{}{}}, []{}() are balanced expressions.

{()}[), {(}) are not balanced.


We can use a stack to solve this problem. We traverse the given expression and

  • If current character in the expression is a opening brace ‘(‘ or ‘{‘ or ‘[‘, we push it to the stack.
  • If current character in the expression is a closing brace ‘)’ or ‘}’ or ‘]’, we pop a character from the stack and we return false if the popped character if not an opening brace or it does not pair with current character of the expression. Also if stack is found to be empty, that means the number of opening braces is less than number of closing brace at that point, so expression cannot be balanced.


Download   Run Code


Download   Run Code


The expression is balanced

The time complexity of above solution is O(n) and auxiliary space used by the program is O(n). Here, n is the length of the input expression.

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of