Generate Parentheses - Problem

Imagine you're designing a bracket balancer that needs to generate all possible valid combinations of parentheses for mathematical expressions. Given n pairs of parentheses, your task is to write a function that generates all combinations of well-formed parentheses.

A well-formed parentheses string means:

  • Every opening parenthesis ( has a corresponding closing parenthesis )
  • Parentheses are properly nested (no closing before opening)
  • The string is balanced (equal number of opening and closing)

Example: For n = 3, valid combinations include "((()))", "(()())", "(())()", "()(())", "()()()"

This problem tests your ability to generate all valid sequences while avoiding invalid ones - a perfect application of backtracking with constraint validation!

Input & Output

example_1.py — Basic Case
$ Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
💡 Note: For n=3, we need 3 pairs of parentheses. All 5 possible well-formed combinations are shown, each using exactly 3 opening and 3 closing parentheses in valid order.
example_2.py — Small Case
$ Input: n = 1
Output: ["()"]
💡 Note: With only 1 pair of parentheses, there's exactly one valid combination: one opening followed by one closing parenthesis.
example_3.py — Two Pairs
$ Input: n = 2
Output: ["(())","()()"]
💡 Note: For n=2, there are exactly 2 valid combinations: nested parentheses "(())" and sequential parentheses "()()".

Constraints

  • 1 ≤ n ≤ 8
  • The number of valid combinations follows the Catalan numbers: C(n) = (2n)! / ((n+1)! × n!)
  • Result size will be at most 1430 combinations (when n=8)

Visualization

Tap to expand
Backtracking Decision Tree (n=2)startopen:0 close:0(open:1 close:0((open:2 close:0()open:1 close:1(())open:2 close:2()()open:2 close:2❌ Cannot start with ')'closeCount would exceed openCount✅ Smart pruningOnly explore valid pathsResult: ["(())", "()()"]🎯 Key Insight: Track open/close counts to ensure validityTime: O(4^n/√n) | Space: O(n) recursion depth
Understanding the Visualization
1
Start Empty
Begin with empty string and zero counts
2
Smart Decisions
At each node, add '(' if open < n, add ')' if close < open
3
Valid Paths Only
Never explore invalid combinations
4
Collect Results
When length = 2n, we have a valid combination
Key Takeaway
🎯 Key Insight: Use backtracking with smart constraints (open < n, close < open) to generate only valid parentheses combinations, achieving optimal Catalan number complexity.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
87.6K Views
High Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen