Algorithms · Visualized

Generate Parentheses

Backtracking

Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.

Generates all combinations of n pairs of well-formed (balanced) parentheses. Time: O(4ⁿ / √n) average, O(4ⁿ / √n) worst; space: O(n) recursion depth, output size proportional to Catalan(n).

Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.

Generate Parentheses

Backtracking

Generates all combinations of n pairs of well-formed (balanced) parentheses. At each step, backtracking tries adding an open parenthesis (if there are still opens available) or a close parenthesis (only if it wouldn't make the string invalid, i.e. there are more opens placed than closes so far).

How Generate Parentheses Works

  1. Track the count of open parentheses used and close parentheses used so far, plus the current string being built.
  2. If open count is less than n, you may add an open parenthesis '(' — recurse with that choice.
  3. If close count is less than open count, you may add a close parenthesis ')' — recurse with that choice (this guarantees validity, since you never close more than you've opened).
  4. When the string length reaches 2n, it's a complete, valid combination — record it.
  5. Backtrack after each recursive call to try the other option at that position.

Generate Parentheses Worked Example

Input: 3

Build up: '(' → '((' → '(((' → '((()' → '((())' → '((()))' recorded. Backtrack and try other branches: '(()())', '(())()', '()(())', '()()()' — all 5 valid combinations for n=3 (Catalan number C₃ = 5) are eventually found.

Generate ParenthesesO(4ⁿ/√n)
Only add ")" when close < open, guaranteeing valid strings.
"▌"
results
Step 1 / 27
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Can add '(' (0 open so far)
Python · Backtracking in Code
def generate_parentheses(n):
    out = []
    def build(o, c, cur):
        if len(cur) == 2 * n:
            out.append(cur)
            return
        if o < n:
            build(o + 1, c, cur + '(')
        if c < o:
            build(o, c + 1, cur + ')')
    build(0, 0, '')
    return out

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Generate Parentheses Time & Space Complexity

BestO(4ⁿ / √n) — bounded by the nth Catalan number
AverageO(4ⁿ / √n)
WorstO(4ⁿ / √n)
SpaceO(n) recursion depth, output size proportional to Catalan(n)

When to Use Generate Parentheses

  • Validating/generating balanced structures — useful for compilers, expression parsers, and syntax validators.
  • A classic example of backtracking with implicit pruning (invalid branches are never even attempted).

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.