Skip to the content

Are they balanced?

Problem

Code editors warn you when a line forgot to close a parenthesis. You are going to write that check.

Write a function that takes a text and returns true if every parenthesis, bracket and brace that opens has its own one closing it, in the right order.

The rules: "([{}])" is balanced and "([)]" is not, because the parenthesis closes before the bracket is done. Anything that is not one of those six characters does not count, so "(2 + 3)" is balanced. An empty text has nothing open, so with it you return true.

A hint: keep what you open in a list, and drop the last one every time something closes correctly.

Examples

  • One pair

    "[]" → true

  • Empty text

    "" → true

  • Never closed

    "[[" → false

  • Backwards

    "}{" → false

  • Nested

    "{[]}" → true

  • Closes the wrong one

    "{[])" → false

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def is_balanced(text):
    pass

JavaScript

function isBalanced(text) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →