DEV Community

Sayani Mallick
Sayani Mallick

Posted on

Solving Balanced Parenthesis Problem

A famous interview question on stacks is to solve the balanced parenthesis problem. In this question, the input consists of a series of parenthesis and other characters and the expected output is to print "Balanced" if the bracket sequence is balanced otherwise "Unbalanced".

Example:
INPUT: []{}{}{}[]
OUTPUT:Balanced

INPUT: [{}]{}
OUTPUT:Balanced

ALGORITHM
To solve this problem, we scan through the elements of the string one by one. If the character under consideration is an opening parenthesis "([{", then we push it to the stack.
If the character is a closing parenthesis, then we check whether the stack is empty or not. If the stack is empty, then it means the brackets are unbalanced. However if the stack is not empty, then we check whether the top element on the stack is the corresponding opening parenthesis or not, that is,( for ), { for }, [ for ]. If it is then we continue scanning, else the sequence is unbalanced.
But the algorithm does not end here.
After the entire string has been scanned, we check again whether the stack is empty. If the stack is empty and the previous scanning results(the algorithm followed above) also show that the string is balanced, then we print that the sequence is Balanced.
However if the stack is not empty, then it means that there is some parenthesis whose match has not been found yet, and the sequence is, hence , unbalanced.

stack

Alt Text

Hope this helps you!

Top comments (0)