Generate Parentheses solution explained
Generate Parentheses is solved by backtracking: build the string one character at a time, add an opening bracket while fewer than n have been used, and add a closing bracket only while it would not outnumber the openers. Every branch that reaches length 2n is a valid answer, so no work is wasted on strings that must be thrown away.
By Evin JohnPublished 7 min read
What you need to produce
Given a whole number n, return all strings made of exactly n ( characters and n ) characters that are properly balanced: reading left to right, the number of closers never exceeds the number of openers, and the totals are equal at the end. Order of the output usually does not matter, but ask.
For n = 2 there are two answers, (()) and ()(). Any other arrangement of two openers and two closers, such as )(() or ())(, closes something before it was opened. The counts grow fast after that.
| n | Valid strings | All strings of length 2n |
|---|---|---|
| 1 | 1 | 4 |
| 2 | 2 | 16 |
| 3 | 5 | 64 |
| 4 | 14 | 256 |
| 5 | 42 | 1,024 |
Those counts are the Catalan numbers, which also count binary tree shapes and many other nested structures. You do not need the formula in an interview, but recognizing the sequence helps you talk about complexity.
What the interviewer wants to see
This is a classic introduction to backtracking. The interviewer is watching for three things: that you build answers incrementally rather than generating and filtering, that you state the two rules that keep a prefix valid, and that you can explain why the result is exponential without apologizing for it. When the output itself is exponential in size, no algorithm can be faster than writing it out.
Brute force: make everything, keep the good ones
Each of the 2n positions is either an opener or a closer, so there are 2^(2n) = 4^n candidate strings. Generate each one and check it with a running depth counter that must never go negative and must end at zero. Checking costs O(n), so the total is O(4^n × n). It works for small n and gives you a reference to test the faster version against.
from itertools import product
def balanced_strings_slow(n):
found = []
for chars in product("()", repeat=2 * n):
depth = 0
for ch in chars:
depth += 1 if ch == "(" else -1
if depth < 0:
break
if depth == 0:
found.append("".join(chars))
return foundBacktracking with two counts
Most of those 4^n strings are doomed from early on. A string that starts with ) can never recover, and neither can one that uses n + 1 openers. So never build them. Track how many openers and closers the prefix already has. You may add an opener if fewer than n are used. You may add a closer if fewer closers than openers are used, since that closer has something to match. Any prefix built under those two rules can always be completed, so every branch ends in a valid string.
def balanced_strings(n):
found = []
built = []
def extend(opened, closed):
if len(built) == 2 * n:
found.append("".join(built))
return
if opened < n:
built.append("(")
extend(opened + 1, closed)
built.pop()
if closed < opened:
built.append(")")
extend(opened, closed + 1)
built.pop()
extend(0, 0)
return foundfunction balancedStrings(n) {
const found = [];
const walk = (soFar, opened, closed) => {
if (soFar.length === 2 * n) {
found.push(soFar);
return;
}
if (opened < n) walk(soFar + "(", opened + 1, closed);
if (closed < opened) walk(soFar + ")", opened, closed + 1);
};
walk("", 0, 0);
return found;
}The two versions show the two usual styles. The Python one mutates a shared list and undoes each choice after the recursive call returns, which is the textbook backtracking shape. The JavaScript one passes a fresh string to each call, so there is nothing to undo. The second style is easier to get right; the first allocates less. Either is a fine answer.
A different construction
Every non-empty valid string can be split uniquely as ( A ) B, where A and B are valid strings with fewer pairs in total. Building answers for 0, 1, 2 and so on up to n from that rule is a dynamic programming solution with the same output. It is worth a mention if the interviewer asks for an alternative, but the counter version is quicker to write correctly.
Complexity
| Approach | Time | Extra space beyond the output |
|---|---|---|
| Generate all strings and filter | O(4^n × n) | O(n) per candidate |
| Backtracking with two counters | O(C(n) × n) | O(n) recursion depth |
| Build from smaller answers, ( A ) B | O(C(n) × n) | Lists for every smaller size |
C(n) grows roughly like 4^n divided by n to the power 1.5, so backtracking is much faster than brute force for the same n, yet still exponential. That is unavoidable, since each of the C(n) strings has length 2n and must be written.
Cases to try
- n = 0: one answer, the empty string, or an empty list. Ask which the interviewer expects.
- n = 1: just
(). - Check that the output has no duplicates and that its length matches the Catalan count.
- A larger n such as 8, mainly to confirm recursion depth is not a problem; it is only 2n deep.
Where answers go wrong
- Allowing a closer whenever fewer than n closers are used, instead of fewer than the openers so far. That admits strings like
)(. - Appending the shared list itself to the results in Python, so every result later turns into the same final value. Join it into a string first.
- Forgetting to pop after the recursive call in the mutating style.
- Calling the solution polynomial. The output alone is exponential.
Follow-ups
- Three bracket kinds. Track a stack of open kinds as well as counts, since a closer must match the most recent opener's kind.
- Only count the strings. Use the Catalan recurrence or a small dynamic program, with no strings built at all.
- Return them in sorted order. Try the opener before the closer at each step, and the search already produces sorted output.
- Generate lazily. Turn the function into a generator so callers can stop early.
Talking it through
Fictional example
- Candidate
- I'll build strings left to right and only make moves that keep the prefix completable. Add an opener if I've used fewer than n. Add a closer if it has an opener to match.
- Candidate
- With those two rules, every branch that reaches length 2n is valid, so nothing gets generated and then thrown away.
- Candidate
- The answer count is the Catalan number, which grows exponentially, so the runtime is about that count times n. You can't beat it, because that's the size of the output.
Where to go from here
Valid Parentheses checks a given bracket string instead of building all of them. Evaluate Reverse Polish Notation and Car Fleet keep to the stack theme, and the coding problems hub lists every walkthrough by pattern.
Using Natively to rehearse
On Mac or Windows, Natively can read a backtracking prompt like this from a screenshot during practice, suggest the two pruning rules, and talk through the complexity argument if it trips you up. It transcribes the mock round as well, so you can reread how you justified the exponential runtime. The AI assistant for coding interviews page describes the coding features.
Questions people ask
How do you solve Generate Parentheses?
Backtrack while tracking how many openers and closers the prefix has. Add an opener while fewer than n are used, and a closer while closers are fewer than openers. Every string that reaches length 2n is valid.
What is the time complexity of Generate Parentheses?
About the nth Catalan number times n, since that many valid strings of length 2n are produced. The Catalan numbers grow roughly like 4^n divided by n to the 1.5, so the work is exponential but far below brute force.
How many valid parentheses strings are there for n pairs?
The nth Catalan number: 1, 2, 5, 14 and 42 for n from 1 to 5.
Is Generate Parentheses backtracking or dynamic programming?
It is usually taught as backtracking. It can also be built bottom-up from smaller answers using the rule that every valid string is ( A ) B for smaller valid A and B.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
