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
·
0depth
·
1·
2·
3·
4·
5SetBalanced strings (0)
empty
1/27
Narrationstep 1 of 27
Build length 6 string using open ≤ n and close ≤ open.
Variables
open=0
close=0
depth=0
cur=
How to think about it
- Invariant: at any point, close ≤ open; never append ')' first.
- At length 2n the string is guaranteed balanced.
- 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