The problem
Return True if the brackets in s are balanced: every opening bracket ( [ { is closed later by the matching closing bracket, and pairs do not cross. Return False otherwise. Every other character is ignored.
balanced('{[()()]}') # True
balanced('([)]') # False: the pairs cross
balanced('print(a[i] + f(x))') # True
balanced('((') # False: never closed
Limits
shas up to 300,000 characters, and brackets can be nested 100,000 deep.
Builds on STAQ-1 Last in, first out and STAQ-2 Brackets and expressions.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
10 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Nested | Not run | |
| 2 | Crossed | Not run | |
| 3 | Empty text | Not run | |
| 4 | Never closed | Not run | |
| 5 | Close first | Not run | |
| 6 | Wrong closer | Not run | |
| 7 | Other characters | Not run | |
| 8 | Only closers | Not run | |
| 9 | 100,000 deep | Not run | |
| 10 | Long and almost right | Not run |