Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an integer n between 1 and 8. Return all strings made of exactly n opening ( and n closing ) brackets that are well-formed: reading left to right, you never close a bracket that wasn't opened, and everything opened is closed by the end. Any order of the list is fine.
Example: n = 3 → ["((()))", "(()())", "(())()", "()(())", "()()()"].
Start with brute force
Every candidate is a string of length 2n where each position is ( or ). Generate all 2^(2n) of them, and keep the ones that pass a balance check (a counter that never goes negative and ends at 0).
It's correct, and for n = 8 it's 65,536 strings, of which only 1,430 are valid. Over 97% of the work is thrown away. At n = 15 it would be over a billion strings. The waste comes from building strings like "))..." that were dead from their very first character.
Building the intuition
Instead of building whole strings and checking them at the end, check while building. Stop the moment a prefix can't possibly become valid.
So when is a prefix still fixable? Think about the counter from Valid Parentheses with one bracket type: +1 for (, −1 for ). A prefix is fine as long as the counter never dips below zero. In other words, you never close more than you've opened.
That gives two rules for the next character, using open and close as the counts so far:
- Add
(ifopen < n. You still have opening brackets left to place. - Add
)ifclose < open. There's an unmatched(waiting to be closed.
If you only ever make legal moves, every string that reaches length 2n is valid. No checking needed at the end, and no dead branches are ever explored.
This "try a choice, go deeper, then undo the choice" style is called backtracking. You'll use it all through the Backtracking & Graphs stage. Here's a gentle first taste.
The optimal approach
- Keep a
path(the characters chosen so far), plusopenandclosecounts. - Write a recursive
build(open, close):- If
pathhas length2n, add it to the result and return. - If
open < n: append(, callbuild(open + 1, close), then remove the(. - If
close < open: append), callbuild(open, close + 1), then remove the).
- If
- Call
build(0, 0)and return the result.
The subtle detail is the undo step. path is shared by every call. After exploring "put ( here", you must remove it before trying "put ) here", or the second branch would start from the wrong prefix. In Python and JavaScript we use a list and pop; in Java a StringBuilder and deleteCharAt; in C++ a string and pop_back.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = []
path = [] # the string built so far, as a list for cheap append/pop
def build(open_count: int, close_count: int) -> None:
if len(path) == 2 * n:
result.append("".join(path))
return
# we may open as long as we still have openers left
if open_count < n:
path.append("(")
build(open_count + 1, close_count)
path.pop()
# we may close only if there is an unmatched opener to close
if close_count < open_count:
path.append(")")
build(open_count, close_count + 1)
path.pop()
build(0, 0)
return resultclass Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
string path; // the string built so far
build(n, 0, 0, path, result);
return result;
}
private:
void build(int n, int openCount, int closeCount, string& path, vector<string>& result) {
if ((int)path.size() == 2 * n) {
result.push_back(path);
return;
}
// we may open as long as we still have openers left
if (openCount < n) {
path.push_back('(');
build(n, openCount + 1, closeCount, path, result);
path.pop_back();
}
// we may close only if there is an unmatched opener to close
if (closeCount < openCount) {
path.push_back(')');
build(n, openCount, closeCount + 1, path, result);
path.pop_back();
}
}
};class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
build(n, 0, 0, new StringBuilder(), result); // path = the string built so far
return result;
}
private void build(int n, int openCount, int closeCount, StringBuilder path, List<String> result) {
if (path.length() == 2 * n) {
result.add(path.toString());
return;
}
// we may open as long as we still have openers left
if (openCount < n) {
path.append('(');
build(n, openCount + 1, closeCount, path, result);
path.deleteCharAt(path.length() - 1);
}
// we may close only if there is an unmatched opener to close
if (closeCount < openCount) {
path.append(')');
build(n, openCount, closeCount + 1, path, result);
path.deleteCharAt(path.length() - 1);
}
}
}/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function (n) {
const result = [];
const path = []; // the string built so far, as an array for cheap push/pop
const build = (openCount, closeCount) => {
if (path.length === 2 * n) {
result.push(path.join(""));
return;
}
// we may open as long as we still have openers left
if (openCount < n) {
path.push("(");
build(openCount + 1, closeCount);
path.pop();
}
// we may close only if there is an unmatched opener to close
if (closeCount < openCount) {
path.push(")");
build(openCount, closeCount + 1);
path.pop();
}
};
build(0, 0);
return result;
};Dry run
n = 2. Each row is one call, in the order the recursion makes them.
| path | open | close | can add (? | can add )? |
|---|---|---|---|---|
"" | 0 | 0 | yes | no (nothing open) |
"(" | 1 | 0 | yes | yes |
"((" | 2 | 0 | no (used all n) | yes |
"(()" | 2 | 1 | no | yes |
"(())" | 2 | 2 | length 4 → record | |
back to "(", try ) → "()" | 1 | 1 | yes | no (nothing open) |
"()(" | 2 | 1 | no | yes |
"()()" | 2 | 2 | length 4 → record |
Result: ["(())", "()()"]. The tree never touched a string starting with ).
Complexity
- Time: O(4^n / √n). The number of valid strings is the n-th Catalan number, which grows like
4^n / (n√n). Each one takes O(n) to build and copy, which gives4^n / √n. Because we never explore dead branches, the work is proportional to the output. - Space: O(n) besides the output. The recursion goes at most
2nlevels deep, andpathholds at most2ncharacters.
Edge cases and traps
- Checking
close < ninstead ofclose < open. That allows"())(", which is invalid. The close rule compares againstopen. - Forgetting to undo. If you append without removing, the second branch builds on a polluted prefix.
- Building new strings on every call.
build(path + "(")also works, because each call gets its own copy. It's simpler but copies O(n) characters at every node. Fine forn ≤ 8. Just know why the append/undo version is leaner. n = 1. Only"()". The rules handle it.
Say it in the interview
"I'll build the strings character by character and only make legal moves, which is backtracking. I can add an opening bracket while I've used fewer than n, and a closing bracket only while closes are fewer than opens, so I never close something that isn't open. When the string reaches length 2n it's guaranteed valid, so I record it. I undo each choice after recursing. The work is proportional to the number of answers, the Catalan number, so about 4^n over root n time, with O(n) extra space for the recursion."
Follow-ups interviewers ask
- "How many strings are there for a given n?" The n-th Catalan number,
C(2n, n) / (n + 1): 1, 2, 5, 14, 42, … Forn = 8it's 1,430. - "Can you do it without recursion?" Yes. Use an explicit stack of
(path, open, close)states, or build up by length with dynamic programming: every valid string is"(" + A + ")" + Bfor smaller valid strings A and B. - "What if there are three bracket types?" Keep a stack of currently open types. A closer must match the top, just like in Valid Parentheses.
Practise the same idea
This is Day 32 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free