Generate Parentheses
LeetCode 22 · Medium · solution, intuition & step-by-step walkthrough
Add '(' if left < n; add ')' if right < left.
This is how I solved Generate Parentheses (LeetCode 22), a medium problem from the Generate / Build Strings pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Build the string character by character. You may add '(' while fewer than n are used, and ')' only if it would close an open one (closing count < opening count). That rule generates exactly the valid strings.
Approach
- 1
Length 2n → record.
- 2
If left < n, append '(' and recurse.
- 3
If right < left, append ')' and recurse.
- 4
Pop after each recursion.
How I solved it
Backtracking with countsPythonCatalan-number time
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
#maintain ( for left parentheses
#maintain ) for right parentheses
res = []
def dfs(cur_string,left_counter,right_counter):
if len(cur_string)==2*n:
res.append("".join(cur_string))
if left_counter<n:
cur_string.append("(")
dfs(cur_string,left_counter+1,right_counter)
cur_string.pop()
#when come back remove (
if left_counter>right_counter: # we have more (
cur_string.append(")")
dfs(cur_string,left_counter,right_counter+1)
#remove when come back
cur_string.pop()
dfs([],0,0)
return resGenerate Parentheses — FAQ
What is the intuition behind Generate Parentheses?
Build the string character by character. You may add '(' while fewer than n are used, and ')' only if it would close an open one (closing count < opening count). That rule generates exactly the valid strings.
How do you solve Generate Parentheses (LeetCode 22)?
1. Length 2n → record. 2. If left < n, append '(' and recurse. 3. If right < left, append ')' and recurse. 4. Pop after each recursion.
What is the time and space complexity of Generate Parentheses?
Time: O(4ⁿ / √n). Space: O(n). (Accepted approach: Backtracking with counts.)
What are common mistakes in Generate Parentheses?
Never let closes exceed opens.