CodeArchon

mediumStackGoogleAmazonApple

Bracket Blueprint Builder

A code formatter emits every valid nesting of N pairs of brackets for a stress test suite.

Given n pairs of parentheses, generate all combinations of well-formed parentheses.

Choose approach

·
0
depth
·
1
·
2
·
3
·
4
·
5
SetBalanced strings (0)
empty
1/27
Narrationstep 1 of 27

Build length 6 string using open ≤ n and close ≤ open.

1def generateParenthesis(n):
2 out, cur = [], []
3 def dfs(o, c):
4 if len(cur) == 2*n:
5 out.append(''.join(cur)); return
6 if o < n:
7 cur.append('('); dfs(o+1, c); cur.pop()
8 if c < o:
9 cur.append(')'); dfs(o, c+1); cur.pop()
10 dfs(0, 0); return out
Variables
open=0
close=0
depth=0
cur=

How to think about it

  1. Invariant: at any point, close ≤ open; never append ')' first.
  2. At length 2n the string is guaranteed balanced.
  3. Count = Catalan number C(n).

Edge cases to catch in interview

  • n = 0 -> one empty string.
  • n = 1 -> only '()'.

Examples

Example 1["((()))","(()())","(())()","()(())","()()()"]
{"n":3,"values":["·","·","·","·","·","·"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed