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: All Valid CombinationsInputn = 22 pairs of ( )Generate All Valid Combinations✓ (()) - nested✓ ()() - sequential✗ )(() - invalid✗ ())) - invalidOutput["(())", "()()"]Rules for Valid Parentheses:1. Equal number of ( and )2. Never more ) than ( at any point🎯 Key Insight: Use backtracking to build valid strings step by step
Understanding the Visualization
1
Input
Given n pairs of parentheses to arrange
2
Process
Generate all valid balanced combinations
3
Output
Return array of valid parentheses strings
Key Takeaway
🎯 Key Insight: Track open/close counts during backtracking to ensure we never violate parentheses balance rules
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