STAQ-P1

Brackets in order

Practice 1 of 6Stacks and queues10 tests

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

  • s has 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

10 tests, not run yet
Test results
#TestResultReads · time
1NestedNot run
2CrossedNot run
3Empty textNot run
4Never closedNot run
5Close firstNot run
6Wrong closerNot run
7Other charactersNot run
8Only closersNot run
9100,000 deepNot run
10Long and almost rightNot run