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.
- The text holds only the characters
(,),[and]. It has at most 50 characters, and it can be empty. - 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. - A closing bracket when no bracket is open makes the text not balanced.
- Every opening bracket must be closed by the end of the text. Empty text is balanced.
- Return
Truein Python ortruein Java when the brackets are balanced, andFalseorfalsewhen 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)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.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)