Generate Parentheses (LeetCode 22): Solution and Explanation
Given a number n, produce every string made of n opening and n closing parentheses that is balanced, meaning every closing parenthesis matches an earlier opening one.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force generates all 2^(2n) strings of length 2n made of the two characters and keeps only the balanced ones, checking each in O(n). For n = 8 that is 65,536 strings, most of them invalid, like strings that start with a closing parenthesis. Nearly all the work is spent building garbage.
A better approach is to never build an invalid prefix in the first place. A prefix can still be completed into a valid string if two rules hold: the number of opening parentheses is at most n, and the number of closing parentheses never exceeds the number of opening ones. Any prefix that breaks either rule is a dead end, and any prefix that respects both can be finished.
So build the string one character at a time and track open_count and close_count. You may add an opening parenthesis whenever open_count < n. You may add a closing one only when close_count < open_count, which guarantees there is an unmatched opener to pair it with. When the string reaches length 2n, both counts equal n and the string is balanced, so it goes straight into the result with no separate check.
Every branch of this recursion ends in a valid answer, which means the work is proportional to the output size. The number of valid strings is the n-th Catalan number, which grows roughly like 4^n divided by n to the power of 1.5.
Approach: Backtracking with open and close counts
- Create an empty
resultlist. - Define
backtrack(open_count, close_count, path). Iflen(path) == 2 * n, appendpathand return. - If
open_count < n, recurse with one more opener:backtrack(open_count + 1, close_count, path + '('). - If
close_count < open_count, recurse with one more closer:backtrack(open_count, close_count + 1, path + ')'). - Start with
backtrack(0, 0, '')and returnresult.
Step-by-step example
n = 2
- Start with an empty path and counts (0, 0). Only an opener is allowed, giving "(" with counts (1, 0).
- From "(", add another opener to get "((" with (2, 0). Now no more openers are allowed, so add closers: "(()" and then "(())", which has length 4 and is recorded.
- Back at "(", the closer branch is allowed because 0 < 1, giving "()" with (1, 1).
- From "()", a closer is not allowed since the counts are equal, so add an opener to get "()(" and then a closer to get "()()", which is recorded.
- The result is ["(())", "()()"], the two balanced strings for n = 2.
Code: Python, Java, C++
1class Solution:
2 def generateParenthesis(self, n: int) -> List[str]:
3 result = []
4
5 def backtrack(open_count, close_count, path):
6 if len(path) == 2 * n:
7 result.append(path)
8 return
9 if open_count < n:
10 backtrack(open_count + 1, close_count, path + '(')
11 if close_count < open_count:
12 backtrack(open_count, close_count + 1, path + ')')
13
14 backtrack(0, 0, '')
15 return result1class Solution {
2 public List<String> generateParenthesis(int n) {
3 List<String> result = new ArrayList<>();
4 backtrack(n, 0, 0, new StringBuilder(), result);
5 return result;
6 }
7
8 private void backtrack(int n, int open, int close, StringBuilder path, List<String> result) {
9 if (path.length() == 2 * n) {
10 result.add(path.toString());
11 return;
12 }
13 if (open < n) {
14 path.append('(');
15 backtrack(n, open + 1, close, path, result);
16 path.deleteCharAt(path.length() - 1);
17 }
18 if (close < open) {
19 path.append(')');
20 backtrack(n, open, close + 1, path, result);
21 path.deleteCharAt(path.length() - 1);
22 }
23 }
24}1class Solution {
2public:
3 vector<string> generateParenthesis(int n) {
4 vector<string> result;
5 string path;
6 backtrack(n, 0, 0, path, result);
7 return result;
8 }
9
10 void backtrack(int n, int open, int close, string& path, vector<string>& result) {
11 if (path.size() == 2 * n) {
12 result.push_back(path);
13 return;
14 }
15 if (open < n) {
16 path.push_back('(');
17 backtrack(n, open + 1, close, path, result);
18 path.pop_back();
19 }
20 if (close < open) {
21 path.push_back(')');
22 backtrack(n, open, close + 1, path, result);
23 path.pop_back();
24 }
25 }
26};Time and space complexity
O(4^n / √n)
The recursion only produces valid strings, and there are about 4^n / (n√n) of them, the n-th Catalan number. Each one takes O(n) to build, which gives O(4^n / √n) overall.
O(n)
The recursion depth is 2n and each frame holds a path of at most 2n characters, not counting the output list.
Other approaches
Generate all and filter (time O(n × 4^n), space O(n))
Build every string of length 2n from the two characters and keep the balanced ones with a counter check. It is easy to write but explores all 2^(2n) strings and validates each in O(n).
Closure number recursion (time O(4^n / √n), space O(4^n / √n))
Every valid string can be written uniquely as ( + A + ) + B, where A and B are valid strings with sizes adding up to n - 1. Combine the results for smaller sizes, optionally memoized. It builds intuition for why the count is a Catalan number.
Common mistakes
- Allowing a closer when
close_count < ninstead ofclose_count < open_count, which produces strings like ")(" that are not balanced. - Using
ifandelsebetween the two branches. Both branches can be valid at the same time and both must be explored. - Using a shared mutable list for the path and forgetting to pop after each call, which corrupts later strings.
- Running a separate validity check on each finished string. The two rules already guarantee every completed string is balanced.
Frequently asked questions
How many valid parentheses strings are there for n pairs?
The count is the n-th Catalan number, which is (2n)! / ((n + 1)! × n!). For n = 3 there are 5 strings and for n = 8 there are 1,430.
What is the time complexity of Generate Parentheses?
It is O(4^n / √n). The backtracking only visits prefixes that can be completed, so the work is proportional to the Catalan number of results times the length of each.
Why is backtracking better than generating every string?
Backtracking stops a branch the moment it becomes invalid, so it never builds the exponentially many unbalanced strings. Every leaf it reaches is an answer.
Can this be solved with dynamic programming?
Yes. Build the answers for each size from smaller ones using the decomposition ( A ) B. It produces the same strings but stores the intermediate lists for every smaller n.