Stacks and queues · Problem 1 of 3

Check that a template's brackets are balanced

Pattern: Valid Parentheses with a Stack

easyNot solved yet

The problem

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.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.