Generate Parentheses - Problem

Given n pairs of parentheses, write a function to generate 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 matching opening)
  • All parentheses are matched

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

Input & Output

Example 1 — Basic Case
$ Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
💡 Note: For n=3, we need 3 opening and 3 closing parentheses. The 5 valid combinations are: ((())), (()()), (())(), ()(())], and ()()().
Example 2 — Minimum Case
$ Input: n = 1
Output: ["()"]
💡 Note: With only 1 pair of parentheses, there's only one valid combination: ()
Example 3 — Small Case
$ Input: n = 2
Output: ["(())","()()"]
💡 Note: For n=2, we have 2 valid ways to arrange 2 pairs: nested (()) or sequential ()()

Constraints

  • 1 ≤ n ≤ 8

Visualization

Tap to expand
Generate Parentheses INPUT Number of pairs n = 3 3 opening + 3 closing ( ( ( ) ) ) Goal: Arrange into valid combinations Constraint: open count >= close at any position ALGORITHM STEPS 1 Backtracking Setup Track open/close counts 2 Add '(' if open < n Can add opening paren 3 Add ')' if close < open Can add closing paren 4 Save when length=2n Valid combination found Decision Tree (partial) ( (( () ((( (() FINAL RESULT 5 valid combinations found ((())) (()()) (())() ()(()) ()()() OK - All Valid! Key Insight: Backtracking explores all possibilities by adding '(' when open count < n, and ')' when close count < open count. This ensures every generated string is well-formed. Time complexity: O(4^n / sqrt(n)) - Catalan number. TutorialsPoint - Generate Parentheses | Backtracking Approach
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
52.0K Views
High Frequency
~15 min Avg. Time
1.5K 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