Skip to content
ExamSpine

Lesson 5.15 · Write it

Do the brackets match?

A functionPython or Java17 tests, 11 of them hidden

On a phone? Put the lines in order instead

A calculator app checks the brackets in a sum before it works the sum out. Write a function that is given just the brackets of a sum, in order, and returns whether they are balanced.

  1. The text holds only the characters (, ), [ and ]. It has at most 50 characters, and it can be empty.
  2. Each closing bracket must close the most recent opening bracket that is still open, and it must be the same kind: ) closes (, and ] closes [. So ([]) is balanced, but ([)] is not.
  3. A closing bracket when no bracket is open makes the text not balanced.
  4. Every opening bracket must be closed by the end of the text. Empty text is balanced.
  5. Return True in Python or true in Java when the brackets are balanced, and False or false when they are not.

Only the value your function returns is checked.

def balanced_brackets(text: str) -> bool

Examples

Your function is tested on 17 cases: the 6 examples below, and 11 hidden ones that check the rules above.

  • balanced_brackets("([])") should return True: the [ opened last, so it closes first (rule 2)
  • balanced_brackets("(]") should return False: a ] cannot close a ( (rule 2)
  • balanced_brackets("((") should return False: two brackets are never closed (rule 4)
  • balanced_brackets(")(") should return False: the ) comes when no bracket is open (rule 3)
  • balanced_brackets("()[]") should return True: two pairs, one after the other (rule 2)
  • balanced_brackets("[)") should return False: a ) cannot close a [ (rule 2)

public static boolean balancedBrackets(String text)

Checking whether Java answers can run here.

Examples

Your function is tested on 17 cases: the 6 examples below, and 11 hidden ones that check the rules above.

  • balancedBrackets("([])") should return true: the [ opened last, so it closes first (rule 2)
  • balancedBrackets("(]") should return false: a ] cannot close a ( (rule 2)
  • balancedBrackets("((") should return false: two brackets are never closed (rule 4)
  • balancedBrackets(")(") should return false: the ) comes when no bracket is open (rule 3)
  • balancedBrackets("()[]") should return true: two pairs, one after the other (rule 2)
  • balancedBrackets("[)") should return false: a ) cannot close a [ (rule 2)
solution.pySolution.java