Python coding

Balanced brackets up to a depth

Return every string of n pairs of round brackets that is balanced and never nests deeper than max_depth. Balanced means each ( is closed by a later ), and reading left to right never shows more ) than ( so far. A string's depth is the most brackets open at once: "(())()" has depth 2, "()()()" depth 1. Return each string once, in any order; for n = 0 the only answer is the empty string.

0 ≤ n ≤ 11, 1 ≤ max_depth ≤ 11.

Besides the tests, one large input (11 pairs, depth at most 2) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • balanced_strings(3, 3) → ["((()))","(()())","(())()","()(())","()()()"]
  • balanced_strings(3, 1) → ["()()()"]
  • balanced_strings(3, 2) → ["(()())","(())()","()(())","()()()"]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Build the string left to right, one bracket per level. Count the ( and ) placed so far: those two numbers decide which brackets are still allowed next.

Hint 2

Add ( while fewer than n are opened and opened − closed < max_depth; add ) only while closed < opened. Every path that follows these rules is valid, so nothing needs checking at the end.

Solution and why it works
pythonO(n·Cₙ), Cₙ = the n-th Catalan number, the answer count with no cap · O(n) recursion depth, beyond the output
def balanced_strings(n: int, max_depth: int) -> list[str]:
    res, path = [], []

    def bt(opened: int, closed: int) -> None:
        if closed == n:
            res.append("".join(path))
            return
        if opened < n and opened - closed < max_depth:
            path.append("(")             # room for one more, and not too deep
            bt(opened + 1, closed)
            path.pop()
        if closed < opened:
            path.append(")")             # only close what is open
            bt(opened, closed + 1)
            path.pop()

    bt(0, 0)
    return res

Two rules decide each step: a ( is allowed while fewer than n have been opened and fewer than max_depth are open now; a ) only while there is something to close. Every branch that obeys them ends in a valid string, so the search hits no dead ends and its cost grows with the output. The trap is generating all 2²ⁿ bracket strings and filtering: for n = 11 and a depth of 2 that is 4,194,304 candidates for 1,024 answers.