LeetCode #22 Medium

Generate Parentheses

Generate Parentheses is LeetCode 22 (Medium). Given n, return every string of n opening and n closing brackets that is well-formed: each ( is closed by a later ), and no ) appears before an open bracket it can close. The strings can be returned in any order.

  • n is at most 8, which gives 1,430 strings, so listing all of them is the job.
Constraints
  • 1 <= n <= 8
backtrackingrecursionstrings
Open on LeetCode ↗
02

Intuition

Build the string one bracket at a time and only add a bracket that can still lead to a valid string. Two counts decide that:

  • Open: ( is allowed while fewer than n have been used.
  • Close: ) is allowed only while there are more opens than closes, so some open bracket is waiting for it.

A prefix that obeys both rules can always be finished, by closing every open bracket. So the search never walks into a dead end, and every string it completes at length 2n is a valid answer.

How to spot this pattern

"List every arrangement that satisfies a rule" with tiny input is backtracking. If the rule can be checked on a prefix, check it before adding each character instead of filtering finished strings.

03

Approach

Try it first

Before reading on, write the condition for adding ( and the condition for adding ) using only two counts: opens used and closes used. Then check that a prefix following both rules can always be completed.

1

Track the brackets used so far

Keep the current string as a list path, plus opened and closed, the counts of each bracket in it. Start with an empty path and both counts at 0.

2

Add an open bracket while any are left

If opened < n, append (, recurse with opened + 1, then pop it off. Popping restores the path, so the same list can try the next choice at this position.

3

Add a close bracket only if one is waiting

If closed < opened, append ), recurse with closed + 1, then pop. This keeps every prefix with at least as many opens as closes, which is exactly what well-formed means.

4

Record the string at full length

When path has 2n characters, both counts equal n, so join it and add it to the result. No final check is needed, because the two rules were enforced at every step.

5

Why each answer appears exactly once

A valid string is a list of choices that the two rules allow, so the search follows that exact path and records it. Two different paths differ at some position, so the same string is never recorded twice.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def generateParenthesis(self, n: int) -> List[str]:
▶6 result, path = [], []
▶7 
▶8 def build(opened: int, closed: int) -> None:
▶9 if len(path) == 2 * n:
▶10 result.append("".join(path))
▶11 return
▶12 if opened < n:
▶13 path.append("(")
▶14 build(opened + 1, closed)
▶15 path.pop()
▶16 if closed < opened:
▶17 path.append(")")
▶18 build(opened, closed + 1)
▶19 path.pop()
▶20 
▶21 build(0, 0)
▶22 return result
opens minus closesno ( leftnothing to close✕pathempty0 open, 0 closedfoundnone yetempty path: only ( can start
pathempty
opened0
closed0
The path starts empty. A close bracket would have nothing to close, so the only move is an open bracket.
opens minus closesno ( leftnothing to closepath(1 open, 0 closedfoundnone yetadd ( → both allowed next
path(
opened1
closed0
Added ( to get (. Opens are left and 1 bracket is waiting to be closed, so both moves stay possible; the open one is tried first.
opens minus closesno ( leftnothing to closepath((2 open, 0 closedfoundnone yetadd ( → both allowed next
path((
opened2
closed0
Added ( to get ((. Opens are left and 2 brackets are waiting to be closed, so both moves stay possible; the open one is tried first.
opens minus closesno ( leftnothing to close✕path(((3 open, 0 closedfoundnone yetadd ( → no ( left, only ) next
path(((
opened3
closed0
Added ( to get (((. All 3 opens are used, so the path can only go down from here.
opens minus closesno ( leftnothing to close✕path((()3 open, 1 closedfoundnone yetadd ) → no ( left, only ) next
path((()
opened3
closed1
Added ) to get (((), coming back from the last branch to try the other move. No opens are left, so only closes can follow.
opens minus closesno ( leftnothing to close✕path((())3 open, 2 closedfoundnone yetadd ) → no ( left, only ) next
path((())
opened3
closed2
Added ) to get ((()), coming back from the last branch to try the other move. No opens are left, so only closes can follow.
opens minus closesno ( leftnothing to closepath((()))3 open, 3 closedfound((()))full length → answer 1 recorded
path((()))
found1
((())) has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.
opens minus closesno ( leftnothing to closepath(()2 open, 1 closedfound((()))add ) → both allowed next
path(()
opened2
closed1
Added ) to get ((), coming back from the last branch to try the other move. Opens are left and a bracket is still waiting, so both moves are possible.
opens minus closesno ( leftnothing to close✕path(()(3 open, 1 closedfound((()))add ( → no ( left, only ) next
path(()(
opened3
closed1
Added ( to get (()(. All 3 opens are used, so the path can only go down from here.
opens minus closesno ( leftnothing to close✕path(()()3 open, 2 closedfound((()))add ) → no ( left, only ) next
path(()()
opened3
closed2
Added ) to get (()(), coming back from the last branch to try the other move. No opens are left, so only closes can follow.
opens minus closesno ( leftnothing to closepath(()())3 open, 3 closedfound((()))(()())full length → answer 2 recorded
path(()())
found2
(()()) has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.
opens minus closesno ( leftnothing to close✕path(())2 open, 2 closedfound((()))(()())add ) → nothing to close, only ( next
path(())
opened2
closed2
Added ) to get (()), coming back from the last branch to try the other move. Every open bracket is now closed, so a close is not allowed; only an open bracket can come next.
opens minus closesno ( leftnothing to close✕path(())(3 open, 2 closedfound((()))(()())add ( → no ( left, only ) next
path(())(
opened3
closed2
Added ( to get (())(. All 3 opens are used, so the path can only go down from here.
opens minus closesno ( leftnothing to closepath(())()3 open, 3 closedfound((()))(()())(())()full length → answer 3 recorded
path(())()
found3
(())() has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.
opens minus closesno ( leftnothing to close✕path()1 open, 1 closedfound((()))(()())(())()add ) → nothing to close, only ( next
path()
opened1
closed1
Added ) to get (), coming back from the last branch to try the other move. Every open bracket is now closed, so a close is not allowed; only an open bracket can come next.
opens minus closesno ( leftnothing to closepath()(2 open, 1 closedfound((()))(()())(())()add ( → both allowed next
path()(
opened2
closed1
Added ( to get ()(. Opens are left and 1 bracket is waiting to be closed, so both moves stay possible; the open one is tried first.
opens minus closesno ( leftnothing to close✕path()((3 open, 1 closedfound((()))(()())(())()add ( → no ( left, only ) next
path()((
opened3
closed1
Added ( to get ()((. All 3 opens are used, so the path can only go down from here.
opens minus closesno ( leftnothing to close✕path()(()3 open, 2 closedfound((()))(()())(())()add ) → no ( left, only ) next
path()(()
opened3
closed2
Added ) to get ()((), coming back from the last branch to try the other move. No opens are left, so only closes can follow.
opens minus closesno ( leftnothing to closepath()(())3 open, 3 closedfound((()))(()())(())()()(())full length → answer 4 recorded
path()(())
found4
()(()) has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.
opens minus closesno ( leftnothing to close✕path()()2 open, 2 closedfound((()))(()())(())()()(())add ) → nothing to close, only ( next
path()()
opened2
closed2
Added ) to get ()(), coming back from the last branch to try the other move. Every open bracket is now closed, so a close is not allowed; only an open bracket can come next.
opens minus closesno ( leftnothing to close✕path()()(3 open, 2 closedfound((()))(()())(())()()(())add ( → no ( left, only ) next
path()()(
opened3
closed2
Added ( to get ()()(. All 3 opens are used, so the path can only go down from here.
opens minus closesno ( leftnothing to closepath()()()3 open, 3 closedfound((()))(()())(())()()(())()()()full length → answer 5 recorded
path()()()
found5
()()() has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.
opens minus closesno ( leftnothing to closepathempty0 open, 0 closedfound((()))(()())(())()()(())()()()all 5 strings found
answers5
Every branch has been tried. The search never built an invalid string, so the list holds exactly the 5 well-formed strings, in sorted order because ( is always tried first.
05

Common pitfalls

Allowing a close bracket whenever closes are left

✗ Wrong
if closed < n:
✓ Right
if closed < opened:

Having closes left is not enough; an open bracket must be waiting. With the wrong test, n = 1 returns ["()", ")("], and n = 2 returns six strings, four of them invalid.

Appending without popping

✗ Wrong
path.append("(")
build(opened + 1, closed)
✓ Right
path.append("(")
build(opened + 1, closed)
path.pop()

The shared path keeps the brackets from the branch that just finished, so the next branch starts from a string that is too long. For n = 2 the result is only ["(())"]; "()()" is lost because the path never shrinks back.

06

Complexity

Time
O(4ⁿ / √n)
Space
O(n)
The number of answers is the nth Catalan number, which grows like 4ⁿ / (n√n). Each answer costs O(n) to build and join, and the pruning means no other branches are explored. The space is the recursion depth and path, both 2n, not counting the output.
07

Generate Parentheses FAQ

How many strings are there for a given n?

The nth Catalan number, (2n)! / ((n + 1)! · n!). For n = 1 to 8 that is 1, 2, 5, 14, 42, 132, 429 and 1,430.

Why not build every bracket string and keep the valid ones?

It works, but there are 2²ⁿ strings of length 2n: 65,536 when n = 8, of which only 1,430 are valid. Checking each one costs O(n) too. The two rules stop an invalid string at its first bad bracket, so only the 1,430 valid strings are ever completed.

Can the answers be built from smaller ones?

Yes. Every valid string starts with (, and that bracket's matching ) splits it into ( + A + ) + B, where A has k pairs and B has n − 1 − k. Combining the stored answers for every k builds the list for n from the lists for smaller sizes. It is a dynamic-programming version with the same output, but it keeps every smaller list in memory.