KatInterview

Build All Balanced Bracket Sequences

StringsAuto-graded · 15 test cases
MediumAuto-gradedStringsrecursionbacktrackingcombinatorics

Last updated

Tests recursion with constraint-based pruning to construct valid nested bracket strings without generating invalid candidates.

A bracket sequence is balanced if:

  • Every opening parenthesis ( is paired with a closing parenthesis ) that appears after it.
  • At no point while reading left-to-right does the count of closing parentheses exceed the count of opening parentheses.

For instance, (()) and ()() are balanced. The sequences )(, ((), and ())( are not balanced.

Write a function that takes a non-negative integer n and returns all distinct balanced bracket sequences containing exactly n opening parentheses and n closing parentheses. Each sequence will have total length 2n.

Return the sequences as a list of strings in any order. All returned sequences must be distinct.

Constraints

  • 0 ≤ n ≤ 8
  • Each output string must be balanced.
  • Each output string must contain exactly n opening and n closing parentheses.
  • No duplicate strings in the output.
  • The count of valid sequences equals the nth Catalan number: for n = 8, there are exactly 1,430 valid sequences.

Examples

Example 1

Input: build_balanced_brackets(1)

Output: ['()']

Example 2

Input: build_balanced_brackets(3)

Output: ['((()))', '(()())', '(())()', '()(())', '()()()']

Example 3

Input: build_balanced_brackets(0)

Output: ['']

Hints

Hint 1

Build strings character by character, tracking how many opening and closing brackets you've placed so far.

Hint 2

You can add an opening bracket as long as you haven't used all n of them yet.

Hint 3

You can add a closing bracket only when there are unmatched opening brackets available to pair with it.