Given an expression string exp, write a program to check whether the brackets {}, (), and [] are balanced and properly nested. An expression is considered balanced if every opening bracket has a corresponding closing bracket in the correct order.
Example:
Input:
"[()]{}{[()()]()}"
Output:
Balanced
Input:
"[(])"
Output:
Not Balanced
Algorithm:
- Declare a character stack S.
- Traverse the expression string exp.
- If the current character is a starting bracket (, {, or [, push it to the stack.
- If the current character is a closing bracket ), }, or ], pop from the stack and check if it matches the corresponding opening bracket; if not, the brackets are not balanced.
- After traversal, if the stack is not empty, the brackets are not balanced.
Below image is a dry run of the above approach:

Code Implementation
#include <bits/stdc++.h>
using namespace std;
bool areBracketsBalanced(string expr){
stack<char> s;
char x;
for (int i = 0; i < expr.length(); i++) {
if (expr[i] == '(' || expr[i] == '['
|| expr[i] == '{') {
s.push(expr[i]);
continue;
}
if (s.empty())
return false;
switch (expr[i]) {
case ')':
x = s.top();
s.pop();
if (x == '{' || x == '[')
return false;
break;
case '}':
x = s.top();
s.pop();
if (x == '(' || x == '[')
return false;
break;
case ']':
x = s.top();
s.pop();
if (x == '(' || x == '{')
return false;
break;
}
}
return (s.empty());
}
int main(){
string expr = "{()}[]";
if (areBracketsBalanced(expr))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}
Output
Balanced
Explanation:
- function "areBracketsBalanced" checks if brackets in a string are balanced using a stack.
- stack "s" is used to store opening brackets.
- Traverse each character of the expression.
- Push opening brackets '(', '[', '{' onto the stack.
- For closing brackets ')', ']', '}', pop the top element and check if it matches the corresponding opening bracket.
- If it does not match, return false.
- After traversal, return true if the stack is empty, otherwise return false.