Challenge: Balanced Brackets
Completed
Read a line of text. Print balanced if every ( [ { is closed by the matching bracket in the right order (ignore all other characters), otherwise not balanced.
Input
One line of text.
Output
balanced or not balanced.
Example
Input
{[()()]}Output
balanced
Editor
Python
Hints
Push opening brackets.
A closing bracket must match what you pop.
At the end the stack must be empty.
Solution explanation
The most recent unclosed bracket is always on top, which is exactly the one that must close next.
Show solution
s = input()
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
ok = True
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
ok = False
break
print("balanced" if ok and not stack else "not balanced") 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