Generate Parentheses Solution
Given n pairs of parentheses, generate all combinations of well-formed parentheses.
Problem Statement
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses strings.
Brute Force โ Generate All & Filter
Generate all 2ยฒโฟ strings of length 2n using '(' and ')', then filter only valid ones. Validation uses a stack or counter โ scan left-to-right, increment on '(', decrement on ')'. Valid if counter never goes negative and ends at 0.
| Metric | Value |
|---|---|
| Time | O(2ยฒโฟ ยท n) โ generate + validate |
| Space | O(n) โ recursion depth |
Backtracking โ O(4โฟ/โn)
Build the string character by character using two rules: (1) add '(' if we haven't used all n openers, (2) add ')' only if close < open (there's an unmatched opener to close). This guarantees every generated string is valid โ no filtering needed.
- Base case: When
open == nandclose == nโ add current string to result. - Choice 1: If
open < nโ recursively try adding '('. - Choice 2: If
close < openโ recursively try adding ')'.
close < open?: - If we've placed 3 openers and 2 closers so far, there's 1 unmatched '(' โ so adding ')' is valid.
- If close == open, there's nothing to close, so ')' would create an invalid prefix.
- This single condition ensures validity without any post-filtering.
Visual Walkthrough
Trace through n = 2:
Code โ Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Generate all + filter | O(2ยฒโฟ ยท n) | O(n) | Most candidates invalid |
| Backtracking โ optimal | O(4โฟ/โn) | O(n) | Only valid strings generated. Count = Catalan number. |
- The number of valid parenthesizations of n pairs is the n-th Catalan number Cโ = (2n)! / ((n+1)! ยท n!).
- For n=3: Cโ=5, for n=8: Cโ=1430. The bound O(4โฟ/โn) comes from the asymptotic formula for Catalan numbers.
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| n = 1 | 1 | Only one string: "()". |
| n = 0 | 0 | Edge โ empty string [""] (not in constraints but worth knowing). |
| n = 8 | 8 | Maximum input โ 1430 valid strings. Runs fast. |
StringBuilder. After the recursive call returns, you must deleteCharAt to restore state. With Python's immutable strings (current + "("), this is automatic โ a new string is created each time.