An email template uses (), [] and {}. Write a function that returns whether every bracket in text is closed by the same kind of bracket, in the right order. All other characters should be ignored.
text
1is_balanced("Hi {name}, your order [#{id}] (ships soon)") -> True
2is_balanced("{[}]") -> False
3is_balanced("(()") -> False
4is_balanced("no brackets") -> True
Why "{[}]" fails1 / 3
{↓push
empty
'{' opens: push it.
{[}] fails because } arrives while [ is still open: brackets can nest, but they can't cross.
Write is_balanced(text) in Python or isBalanced(text) in JavaScript. Examples are written in Python: in JavaScript, None is null and True / False are true / false.
Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Write your function, then run it against 24 tests.
Breakdown
Stuck? Reveal one step at a time, and try again after each one.
Counting isn't enough
Counting openers and closers of each kind catches ((), but not {[}], where every count matches. The order matters: a closer has to match the most recent bracket that's still open.
Step 2
The most recent open bracket
"The most recent unfinished thing" is exactly what a stack gives you. Push every opener. The top of the stack is always the bracket that the next closer must match.
Step 3
Handle a closer
When you see a closer, the stack must not be empty, and the top must be the matching opener. If either check fails, return false. Otherwise pop it.
Step 4
Check what's left
After the last character, any opener still on the stack was never closed. Balanced means the stack is empty.
Solution
Give it a real try first: you learn far more from a wrong attempt than from reading the answer.
Map each closer to its opener (')' → '(' and so on). Walk through the text: push openers; for a closer, return false unless the stack's top is its opener, then pop. Ignore everything else. At the end, return whether the stack is empty.