15% off all plans & roadmaps Use code

See plans

Generate Parentheses

Updated

TL;DR: Build every string of n pairs of parentheses that is well-formed. Backtracking with an open count and a close count only ever extends valid prefixes, so no invalid string is ever built.

Problem

Given n pairs of parentheses, write a function that returns all combinations of well-formed parentheses with exactly n pairs. A string is well-formed when every ( is closed by a later ) in the correct order. You may return the strings in any order.

Example 1

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2

Input: n = 1
Output: ["()"]

Constraints

  • 1 <= n <= 8

Constraints that matter

  • n is at most 8, so the answer holds at most 1430 strings (the 8th Catalan number). Any method that builds strings of length 16 one by one is fast enough.
  • The output itself has size about 4^n / sqrt(n) characters, so no algorithm can beat that bound. Your goal is to avoid work on strings that are not in the answer.
  • Brute force over all 2^(2n) strings is still only 65536 strings at n = 8. It passes, but an interviewer will expect you to see that almost all of them are invalid.
  • Recursion depth is 2n, at most 16. Deep-recursion limits in Python or Java are not a concern here.

View on LeetCode

Hints

Hint 1

This is a backtracking problem.

Hint 2

Treat each of the 2n positions as a free choice between ( and ).

Solution

Intuition

This is a backtracking problem. You build the answer one character at a time, and at each position you have at most two choices: add ( or add ). The recursion tree is a binary tree of choices, and your job is to cut off every branch that cannot lead to a valid string.

Picture a doorman counting guests in and out of a room that holds n people. The open count is the guests who have entered, and the close count is the guests who have left.

Pruning is possible because validity can be checked on a prefix. A prefix is still completable if it never has more ) than (, and it never uses more than n of the (. If a prefix breaks either rule, no later character can fix it, so you stop right there.

That gives two counters and two rules. You may add ( while open < n. You may add ) while close < open. Every string the recursion reaches at length 2n then has n opens, n closes, and no prefix with a surplus of closes, so it is well-formed.

There is a second way to see the structure. Every valid string starts with (, and that ( pairs with exactly one ). Between them sits a valid string, and after them sits another valid string. If the inside uses i pairs, the tail uses n - 1 - i.

This gives a dynamic programming build from smaller answers. It also explains why the answer count is the Catalan number.

Watch the pattern animation

Worked example

Input: n = 1
Output: ["()"]
Explanation: One pair gives a string of length 2 with one ( and one ). The strings ((, )) and )( are all invalid, so only () survives. The same single answer comes out of every approach, which makes it a good first trace.

Approach 1: Brute force: try every string and validate

Treat each of the 2n positions as a free choice between ( and ). That gives 2^(2n) strings. For each one, scan left to right with a balance counter and keep the string only if the balance never drops below 0 and ends at 0.

This is correct because it checks the definition directly. It is slow because almost every string is garbage. At n = 8, you inspect 65536 strings to keep 1430.

Steps

  1. Let total = 2 * n. Loop mask from 0 to 2^total - 1.
  2. Read the bits of mask from the most significant to the least. A 0 bit means ( and a 1 bit means ).
  3. Keep a balance counter: add 1 for (, subtract 1 for ).
  4. If the balance goes below 0, mark the string invalid and stop reading it.
  5. After the last bit, keep the string only if it is still valid and the balance is 0.
  6. Return the kept strings. Increasing mask order happens to produce lexicographic order.

Dry run

Trace n = 1, so total = 2 and masks run 0 to 3.

maskbitsstringbalance pathkept
000((1, 2no, ends at 2
101()1, 0yes
210)(-1no, drops below 0
311))-1no, drops below 0

Only () is kept, so the result is ["()"].

Complexity

TimeO(n * 4^n)
SpaceO(n) extra, plus the output

Here n is the number of pairs. There are 2^(2n) = 4^n masks, and each one costs up to 2n steps to scan, so time is O(n * 4^n). Besides the output list, you hold one buffer of length 2n, so extra space is O(n).

PythonTested in our runner

from typing import List

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        total = 2 * n
        result = []
        for mask in range(1 << total):
            balance = 0
            chars = []
            valid = True
            for pos in range(total):
                # bit 0 means '(' and bit 1 means ')'
                if (mask >> (total - 1 - pos)) & 1:
                    balance -= 1
                    chars.append(')')
                else:
                    balance += 1
                    chars.append('(')
                if balance < 0:
                    valid = False
                    break
            if valid and balance == 0:
                result.append(''.join(chars))
        return result

Approach 2: Build from smaller answers (dynamic programming)

What's slow: brute force spends almost all its time on strings that were never going to be valid, such as ))((. It also re-scans each string from scratch to validate it.

The insight that fixes it: every valid string with k pairs has a unique form ( + A + ) + B. Here A is a valid string with i pairs and B is a valid string with k - 1 - i pairs. The first ( pairs with exactly one ), so the split is unique. The list for k pairs therefore comes from the lists for smaller sizes, and every string you build is valid by construction.

Store dp[k] as the list of all valid strings with k pairs. Start from dp[0] = [""]. Looping i from k - 1 down to 0 gives the same order as the expected output for n = 3.

Steps

  1. Create dp as n + 1 empty lists and set dp[0] to the list holding the empty string.
  2. For each k from 1 to n, loop i from k - 1 down to 0.
  3. For each string left in dp[i] and each string right in dp[k - 1 - i], build ( + left + ) + right.
  4. Append every built string to dp[k].
  5. After k reaches n, return dp[n].

Dry run

Trace n = 1.

  • Start: dp[0] = [""].
  • k = 1: the only i is 0. left comes from dp[0] and right comes from dp[1 - 1 - 0] = dp[0].
  • The only pair is left = "" and right = "", which builds ( + "" + ) + "" = ().
  • dp[1] = ["()"], so the result is ["()"].

For a slightly bigger check, dp[2] is built with i = 1 giving (()) and i = 0 giving ()().

Complexity

TimeO(n * 4^n / sqrt(n)) at worst, which is O(4^n / sqrt(n)) in total
SpaceO(4^n / sqrt(n))

Here n is the number of pairs and C(k) is the k-th Catalan number, the count of valid strings with k pairs. Building dp[k] creates C(k) strings of length 2k, so level k costs O(k * C(k)). Since C(k) grows by a factor of about 4 each step, the last level dominates the sum. The total is O(n * C(n)) = O(4^n / sqrt(n)). Space is the same order because you keep every dp[k] list, which is a constant factor more than the output alone.

PythonTested in our runner

from typing import List

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        dp = [[] for _ in range(n + 1)]
        dp[0] = ['']
        for k in range(1, n + 1):
            # i pairs go inside the first '(' and k-1-i pairs go after its ')'
            for i in range(k - 1, -1, -1):
                for left in dp[i]:
                    for right in dp[k - 1 - i]:
                        dp[k].append('(' + left + ')' + right)
        # '(' < ')' in ASCII, so sorting gives the expected lexicographic order
        return sorted(dp[n])
Parentheses Generation pattern infographic for Generate Parentheses

Solution pattern

Parentheses Generation

Part of Backtracking Patterns

Approach 3: Backtracking with open and close countsOptimalParentheses Generation

What's slow in the DP: it keeps a list for every size from 0 to n, so it holds far more strings in memory than the final answer needs. It also creates many intermediate strings by concatenation.

The insight that fixes it: grow one string character by character and prune with two counters. Add ( only while open < n. Add ) only while close < open. Every prefix you reach can be finished into a valid string, so the recursion never hits a dead end.

You keep one shared buffer, append, recurse, then remove the last character. Because there are no dead ends, the number of recursion nodes is at most 2n times the number of answers. That matches the output size, so you do no wasted work beyond a constant factor.

Why it is correct. Every prefix the buffer holds has open at least close and open at most n. Any such prefix can be finished by adding the remaining opens, then the remaining closes, so it is never a dead end. Every valid string's prefixes satisfy both rules, so the pruning never cuts off a branch that leads to one.

Steps

  1. Keep a result list, a mutable path buffer, and a recursive function taking the open count and close count.
  2. If the path has length 2 * n, copy it into the result and return.
  3. If open < n, append (, recurse with open + 1, then remove the last character.
  4. If close < open, append ), recurse with close + 1, then remove the last character.
  5. Call the function with open = 0 and close = 0 and return the result.

Dry run

Trace n = 1. The path starts empty.

StepPathopencloseAction
1``00open < 1, so append (
2(10open is not < 1. close < open (0 < 1), so append )
3()11length is 2, so record () and return
4(10pop ). No more choices, return
5``00pop (. close < open is 0 < 0, false, so return

The result is ["()"].

For n = 2 the tree has two leaves: (()) through (( and ()() through (). At () the close branch is closed because close equals open, so only ( is allowed.

Complexity

TimeO(4^n / sqrt(n))
SpaceO(n) extra, plus the output

Here n is the number of pairs. The recursion has depth 2n, and every node is a prefix of some valid string, so each node lies on a root-to-leaf path. There are C(n) leaves (the n-th Catalan number, about 4^n / (n * sqrt(n))), so there are at most 2n * C(n) nodes.

Each node costs O(1) with a shared buffer, and each leaf pays O(n) to copy the string. Time is therefore O(n * C(n)) = O(4^n / sqrt(n)). The extra space is the recursion stack and the buffer, both of size at most 2n.

PythonTested in our runner

from typing import List

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        result = []
        path = []

        def backtrack(open_used: int, close_used: int) -> None:
            if len(path) == 2 * n:
                result.append(''.join(path))
                return
            if open_used < n:
                path.append('(')
                backtrack(open_used + 1, close_used)
                path.pop()
            # a ')' is allowed only if an unmatched '(' exists
            if close_used < open_used:
                path.append(')')
                backtrack(open_used, close_used + 1)
                path.pop()

        backtrack(0, 0)
        return result

Common mistakes

  • Writing if close < n instead of if close < open for the closing branch. This lets you emit ())( style strings whose totals match but whose order is broken. The fix is to compare against the open count, because a ) needs an unmatched ( before it.
  • Forgetting to undo the choice, for example calling path.append('(') and recursing without path.pop() afterwards. The buffer then keeps stale characters and later strings come out too long or wrong. Remove the last character right after each recursive call returns.
  • Using the wrong base case, such as len(path) == n instead of len(path) == 2 * n. You stop at half the string and return prefixes. The finished string has 2 * n characters.
  • Appending the shared buffer itself to the result, like result.append(path) in Python with a list buffer. Every entry points at the same list, and they all end up empty. Copy it with ''.join(path) or path.toString().
  • Generating all 4^n strings and filtering at the end, then finding it slow or rejected in an interview. Validity of a prefix can be checked as you go, so check it as you go.
  • In the DP, looping i over the wrong range, for example range(k) with dp[k - i], which can pick dp[k] before it is complete. The inside gets i pairs and the tail gets k - 1 - i pairs. The two sizes must add up to k - 1.

Edge cases

  • n = 1: the answer is ["()"], a single string. This is the smallest input and checks the base case.
  • n = 2: the answer is ["(())","()()"]. It checks that the close branch is blocked when close equals open.
  • n = 3: five strings, ["((()))","(()())","(())()","()(())","()()()"]. Any other count points to a missed or duplicated branch.
  • n = 8, the maximum: exactly 1430 strings, each of length 16. This checks that no duplicates appear and that nothing times out.
  • Every returned string must have length 2n with equal counts of ( and ). A quick sanity check is to scan each result and confirm the running balance never goes negative.

Follow-ups interviewers ask

How many strings does the answer contain, and how do you know?
The count is the n-th Catalan number, which is binom(2n, n) / (n + 1). It satisfies C(n) = sum of C(i) * C(n - 1 - i) over i from 0 to n - 1, which is exactly the DP split on the first (. For n = 1 to 8 the values are 1, 2, 5, 14, 42, 132, 429, 1430.
Can you do it with less memory than the output list?
You can stream the answers instead of storing them. Make the backtracking a generator that yields each finished string, and extra space stays at O(n) for the buffer and recursion stack. You cannot go below that, because the recursion needs a path of length 2n.
How would you check whether one given string is valid, and how does that relate to this problem?
Scan it with one counter: add 1 for (, subtract 1 for ). The string is valid if the counter never goes negative and ends at 0. The backtracking enforces the same rule while generating, which is why it never needs a validation pass. This is the Valid Parentheses check reduced to one bracket type.

Generate Parentheses FAQ

What is the time complexity of Generate Parentheses?

It is O(4^n / sqrt(n)), where n is the number of pairs. The output holds the n-th Catalan number of strings, about 4^n / (n * sqrt(n)), each of length 2n. Backtracking with pruning touches at most 2n times that many nodes, so it matches the output size.

Why use backtracking for Generate Parentheses?

You build the string one character at a time and each prefix can be judged valid or invalid immediately. Backtracking lets you cut an invalid prefix the moment it appears, instead of finishing the string and checking it. That removes the exponential waste of the brute force.

Can Generate Parentheses be solved in O(1) extra space?

No. The recursion needs a path of up to 2n characters and a stack of depth 2n, so extra space is O(n). You could build the answers iteratively with an explicit counter-based generator, but you still need to hold the current string of length 2n.

Why is the closing condition close < open and not close < n?

A ) is only legal when some earlier ( is still unmatched. The number of unmatched opens is open minus close, so you need that to be positive. Using close < n allows prefixes such as ) at the start, which can never become valid.

Is the dynamic programming solution better than backtracking for LeetCode 22?

Both have the same time bound, O(4^n / sqrt(n)). Backtracking uses O(n) extra space besides the output, while the DP stores lists for every size up to n. For this problem backtracking is the usual interview answer, and the DP is a good alternative that shows the Catalan structure.

Do the output strings have to be in a specific order?

The problem accepts any order. Backtracking that tries ( before ) returns them in lexicographic order, which matches the sample output for n = 3. The DP in this page loops the inner size from large to small to produce the same order.

Asked at

See which companies ask this — Pro

Practise it