- Interview Questions
- /
- Problems
- /
- Generate Parentheses
Generate Parentheses
List every balanced arrangement of n pairs of parentheses. Backtracking where two simple counters decide which branches are allowed. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
Given a positive integer n, return every string made of exactly n opening and n closing parentheses that is balanced: reading left to right, you never close more parentheses than you have opened, and by the end every opening one has been closed.
Return the strings in any order, with no duplicates.
Example 1
- Input
- n = 2
- Output
- ["(())", "()()"]
With two pairs you can nest them or put them side by side. A string like ")(()" is invalid because it closes before anything is open.
Example 2
- Input
- n = 1
- Output
- ["()"]
Constraints
- 1 ≤ n ≤ 8
- The output has exactly one entry per distinct balanced string.
Practice
Runs 8 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Generate Parentheses in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Generate Parentheses
Pattern: Backtracking with constraints
"Generate all valid X" means backtracking: build the string one character at a time, and only take steps that can still lead to a valid answer.
Here, validity comes down to two counts, opened and closed, of the characters placed so far:
- You can add
(as long asopened < n. - You can add
)only ifclosed < opened, meaning there is an unmatched(to close.
If you follow those two rules, every string you finish is balanced, and you never waste time on a prefix that's already broken. That's the difference from generating all 2^(2n) strings and filtering: the rules prune dead branches before they grow.
Approach 1: Generate everything, then filter
Build all 2^(2n) strings of length 2n and keep the ones whose running balance never goes negative and ends at zero. It is a good correctness check, but most of the work is spent on invalid strings.
Time O(2²ⁿ · n) · Space O(2²ⁿ · n) if you store them all
Approach 2: Backtracking with open and close counts
Define backtrack(opened, closed) working on a shared path:
- If
len(path) == 2n, record"".join(path)and return. - If
opened < n: push(, recurse withopened + 1, pop. - If
closed < opened: push), recurse withclosed + 1, pop.
Every leaf is a distinct balanced string, so the work is proportional to the output: the n-th Catalan number of strings, each of length 2n.
Time O(4ⁿ / √n) · Space O(n) recursion, plus the output
| Approach | Time | Space |
|---|---|---|
| Generate everything, then filter | O(2²ⁿ · n) | O(2²ⁿ · n) if you store them all |
| Backtracking with open and close counts | O(4ⁿ / √n) | O(n) recursion, plus the output |
Solution code
Try the practice editor first. Both solutions pass every test above.
Generate Parentheses solution in Python
def generate_parenthesis(n: int) -> list[str]:
results = []
path = []
def backtrack(opened: int, closed: int) -> None:
if len(path) == 2 * n:
results.append("".join(path))
return
if opened < n:
path.append("(")
backtrack(opened + 1, closed)
path.pop()
if closed < opened:
path.append(")")
backtrack(opened, closed + 1)
path.pop()
backtrack(0, 0)
return resultsGenerate Parentheses solution in JavaScript
function generateParenthesis(n) {
const results = [];
const path = [];
const backtrack = (opened, closed) => {
if (path.length === 2 * n) {
results.push(path.join(''));
return;
}
if (opened < n) {
path.push('(');
backtrack(opened + 1, closed);
path.pop();
}
if (closed < opened) {
path.push(')');
backtrack(opened, closed + 1);
path.pop();
}
};
backtrack(0, 0);
return results;
}Common mistakes
- Allowing `)` whenever `closed < n` instead of `closed < opened`, which produces strings like `())(`.
- Building strings with `path + "("` at every level and also keeping a shared list, mixing two styles and getting stale results.
- Generating duplicates by inserting `()` into every position of the n − 1 answers without de-duplicating.
- Quoting the time as O(2²ⁿ) for the backtracking version, which ignores the pruning; the honest bound is the Catalan number times n.
What interviewers look for
State the two rules before writing any code, and explain why they're enough: the first keeps the total count right, and the second guarantees no prefix ever closes more than it opened. That justification is what the interviewer is listening for.
For complexity, it's fine to say "proportional to the number of valid strings, which is the n-th Catalan number, about 4ⁿ / n^1.5, times n to build each one." Naming Catalan numbers shows you understand why the output grows the way it does.
Follow-up questions
How many strings are there for a given n?
The n-th Catalan number, C(2n, n) / (n + 1): 1, 2, 5, 14, 42, 132, 429, 1430 for n = 1 to 8. It grows roughly like 4ⁿ / (n^1.5 · √π).
Can you build the answers without recursion?
Yes, with dynamic programming: every balanced string of n pairs is "(" + A + ")" + B, where A has i pairs and B has n − 1 − i pairs. Build the lists for 0, 1, ..., n pairs in order and combine them.
What if there are three bracket types, ( [ {, with n pairs total?
Keep a stack of currently open brackets instead of a single counter. You may open any type while fewer than n have been opened, and you may close only the type on top of the stack. The count grows by a factor of 3ⁿ.
Companies that ask Generate Parentheses
Generate Parentheses is tagged by 123 companies in our interview dataset. The score shows how often it comes up at each company.
- Zenefits100%
- D2l97%
- Cribl95%
- Walmart Labs93.3%
- Snapchat93%
- Mercedes Benz91%
- Plaid88%
- Varonis88%
- Disney87.6%
- Angi86%
- Lightmatter85%
- Peraton84%
- Servicenow83.8%
- Forto83%
- Fico83%
- Huawei82.9%
- Ford Motor82%
- Goodnotes79%
- Zoho78.3%
- Sortly77%
- Freshbooks77%
- Grammarly75.8%
- Affinipay75%
- Bumble74%
and 99 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required