Introduction
The Generate Parentheses problem is one of the most important and frequently asked backtracking questions in coding interviews.
At first glance, it may look like a simple string generation problemβbut the real challenge is to generate only valid (well-formed) parentheses combinations.
This problem is a perfect example of:
- Constraint-based recursion
- Backtracking with conditions
- Decision tree pruning
In this article, weβll break down the intuition, understand the constraints, and implement a clean and efficient solution.
π Problem Link
LeetCode: Generate Parentheses
Problem Statement
Given n pairs of parentheses:
π Generate all combinations of well-formed parentheses
Examples
Example 1
Input:
n = 3
Output:
["((()))","(()())","(())()","()(())","()()()"]
Example 2
Input:
n = 1
Output:
["()"]
Key Insight
We are not generating all possible stringsβwe are generating only valid parentheses.
Rules of Valid Parentheses
- Number of
(must equal number of) - At any point:
Intuition (Decision Making)
At every step, we have two choices:
But we cannot always take both choices.
Valid Conditions
When can we add "("?
When can we add ")"?
π This ensures the string always remains valid.
Decision Tree (n = 3)
π You can add your tree diagram here for better visualization.
Conceptual Flow
Invalid paths like ")(" are never explored because of constraints.
Approach: Backtracking with Constraints
Idea
- Keep track of:
- Remaining open brackets
- Remaining close brackets
- Build string step by step
- Only take valid decisions
Java Code
Step-by-Step Execution (n = 2)
Complexity Analysis
- Time Complexity: O(4βΏ / βn) (Catalan Number)
- Space Complexity: O(n) recursion stack
Why Catalan Number?
The number of valid parentheses combinations is:
Why This Approach Works
- It avoids invalid combinations early
- Uses constraints to prune recursion tree
- Generates only valid results
- Efficient compared to brute force
β Naive Approach (Why It Fails)
Generate all combinations of ( and ):
- Total combinations = 2^(2n)
- Then filter valid ones
π Very inefficient β TLE
Key Takeaways
- This is a constraint-based recursion problem
- Always:
- Add
"("if available - Add
")"only if valid - Backtracking avoids invalid paths
- Important pattern for interviews
Common Interview Variations
- Valid parentheses checking
- Longest valid parentheses
- Remove invalid parentheses
- Balanced expressions
Conclusion
The Generate Parentheses problem is a must-know backtracking problem. It teaches how to apply constraints during recursion to efficiently generate valid combinations.
Once mastered, this pattern becomes extremely useful in solving many advanced recursion problems.
Frequently Asked Questions (FAQs)
1. Why canβt we add ")" anytime?
Because it may create invalid sequences like ")(".
2. What is the key trick?
Ensure:
3. Is recursion the best approach?
Yes, it is the most intuitive and efficient method.




