Build All Balanced Bracket Sequences
StringsAuto-graded · 15 test casesLast 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
nopening andnclosing 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Instead of generating all possible strings and filtering for valid ones, we construct only valid sequences by building them incrementally with constraint checks.
We maintain two counters as we build: the number of opening brackets placed and the number of closing brackets placed. At each recursive step, we decide whether to add an opening or closing bracket based on two rules:
- Add an opening bracket if we haven't yet placed all
nopening brackets. - Add a closing bracket only if the number of closing brackets placed so far is less than the number of opening brackets (ensuring there's an unmatched opening bracket to pair with).
When both counters reach n, we've constructed a complete valid sequence of length 2n.
Why It Works
A bracket sequence is balanced if and only if:
- Every prefix has at least as many opening brackets as closing brackets
- The total counts are equal
Our construction guarantees both properties:
- Rule 2 ensures that at every step,
closes_placed ≤ opens_placed, maintaining the prefix invariant. - We terminate only when both counters equal
n, ensuring equal totals.
Every valid sequence corresponds to exactly one path through our recursion tree, so we generate each distinct sequence exactly once with no duplicates.
Complexity
Time: O(C_n × n) where C_n is the nth Catalan number. The number of valid sequences grows as approximately 4^n / (n^(3/2) × √π). For each sequence, we perform O(n) work along its construction path plus O(n) to build the final string. Since our pruning ensures every leaf produces a valid output, we do no wasted work. For n = 8, this produces 1,430 sequences efficiently.
Space: O(n) auxiliary space for the recursion stack and character buffer. The output itself requires O(C_n × n) space, which is inherent to the problem.
Solution
from typing import List
def build_balanced_brackets(n: int) -> List[str]:
result = []
current = []
def build(opens_placed, closes_placed):
if opens_placed == n and closes_placed == n:
result.append(''.join(current))
return
if opens_placed < n:
current.append('(')
build(opens_placed + 1, closes_placed)
current.pop()
if closes_placed < opens_placed:
current.append(')')
build(opens_placed, closes_placed + 1)
current.pop()
build(0, 0)
return result