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
BacktrackingGenerates 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
- Track the count of open parentheses used and close parentheses used so far, plus the current string being built.
- If open count is less than n, you may add an open parenthesis '(' — recurse with that choice.
- 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).
- When the string length reaches 2n, it's a complete, valid combination — record it.
- 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.
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 outBehind 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
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
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.