The Problem

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, the result is:
["((()))", "(()())", "(())()", "()(())", "()()()"]

Interactive Visualization

Speed:
Decision Tree
Open: 0 / 3
Close: 0 / 3
""
Results found: 0
No combinations found yet.
Code
fun generateParenthesis(n: Int): List<String> {    val result = mutableListOf<String>()    fun dfs(openCount: Int, closeCount: Int, current: String) {        if (current.length == 2 * n) {            result.add(current)            return        }        if (openCount < n) {            dfs(openCount + 1, closeCount,                current + "(")        }        if (closeCount < openCount) {            dfs(openCount, closeCount + 1,                current + ")")        }    }    dfs(0, 0, "")    return result}
Status & Log
Press Step or Play to begin.

How It Works

Key Insight

At each position, we can add ( if open_count < n, or ) if close_count < open_count. This ensures we never have more closing than opening parentheses at any point in the string, which is exactly the condition for well-formed parentheses.

The Algorithm

  • DFS with two choices at each step: add an opening paren ( or a closing paren ).
  • Pruning rule 1: only add ( if we haven't used all n opening parens yet (open_count < n).
  • Pruning rule 2: only add ) if doing so won't create an invalid prefix (close_count < open_count).
  • Base case: when the string reaches length 2n, it's a valid combination โ€” add it to the result.
  • The DFS naturally backtracks after exploring each branch, building the complete set of valid combinations.

Complexity

Time O(4n / √n)
Space O(n)

The number of valid parentheses combinations is the n-th Catalan number, which is C(2n, n) / (n+1), bounded by O(4n / n3/2). Each combination takes O(n) to construct, giving O(4n / √n) total work. The recursion depth (and thus space for the call stack) is O(n).