Coding Interview PatternsGenerate Parentheses
MediumSubsets
Generate Parentheses
Explanation & Solution
Description
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
A parentheses string is well-formed if every opening parenthesis ( has a corresponding closing parenthesis ) and the pairs are properly nested.
Input: n = 3
Output:["((()))","(()())","(())()","()(())","()()()"]
0
((()))
1
(()())
2
(())()
3
()(())
4
()()()
Explanation: All 5 valid arrangements of 3 pairs of parentheses.
Constraints
1 <= n <= 8
Approach
Subsets pattern
1. Initialize the Result Array
- Create an empty
resultarray to collect all valid parentheses strings - Start the recursive
backtrackfunction with an empty string and bothopenandclosecounts at 0
2. Base Case — Complete String
- If the current string has length
2 * n, it contains exactlynopening andnclosing parentheses - Add it to
resultand return
3. Add an Opening Parenthesis
- If the count of opening parentheses
openis less thann, we can still add a( - Recurse with the updated string and
open + 1
4. Add a Closing Parenthesis
- If the count of closing parentheses
closeis less thanopen, we can add a) - This condition ensures we never have more closing than opening parentheses at any point, maintaining validity
- Recurse with the updated string and
close + 1
5. Why This Generates All Valid Combinations
- By always trying
(before), the results naturally come out in lexicographic order (since(has a smaller ASCII value than)) - The two constraints (
open < nandclose < open) are necessary and sufficient to guarantee every generated string is well-formed
Key Insight
- The key constraint is
close < open: we can only add a closing parenthesis when there is an unmatched opening parenthesis to close - This simple rule eliminates all invalid strings without needing any explicit validation
- The number of valid strings is the nth Catalan number: C(n) = (2n)! / ((n+1)! * n!)
Time
**O(4^n / sqrt(n))** — proportional to the nth Catalan numberSpace
O(n) for the recursion depthVisualization
Input:
Backtracking Exploration
current path
empty
No animation available
ExploringFoundBacktrack
0 steps