Challenge: Balanced Brackets
Completed
Read a line. Print balanced if every ( [ { is closed by the matching bracket in the right order (ignore other characters), otherwise not balanced.
Input
One line of text.
Output
balanced or not balanced.
Example
Input
{[()()]}Output
balanced
Editor
C++
Hints
Push opening brackets.
A closing bracket must match the top; then pop.
The stack must be empty at the end.
Solution explanation
The most recent unclosed bracket is always on top.
Show solution
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
string t;
getline(cin, t);
stack<char> s;
bool ok = true;
for (char ch : t) {
if (ch == '(' || ch == '[' || ch == '{') s.push(ch);
else if (ch == ')' || ch == ']' || ch == '}') {
char want = ch == ')' ? '(' : ch == ']' ? '[' : '{';
if (s.empty() || s.top() != want) { ok = false; break; }
s.pop();
}
}
cout << (ok && s.empty() ? "balanced" : "not balanced") << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module