Skip to content

Generate Parentheses

Build every balanced string of n pairs of parentheses, adding a bracket only while it can stay valid.

MediumBacktracking
Solve on LeetCode

The problem

You get an integer n. Return every string of n opening and n closing parentheses that is well-formed: each ( is matched by a later ), and no ) appears before the ( it closes. The strings can be in any order.

Input n = 2

Output ["(())", "()()"]

Two pairs can be nested or placed side by side.

Input n = 4

Output ["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]

Four pairs already give 14 different well-formed strings.

Key constraint: n is at most 8, and the number of valid strings grows fast (1,430 for n = 8), so the aim is to never build an invalid one.

How to spot the pattern

  • You must generate every string that follows a rule, not just count them.
  • Each position has only two choices, and two counters tell you which ones are still allowed.

The idea

Build the string from left to right. You may add ( as long as fewer than n of them have been used. You may add ) only when it has something to close, that is, when fewer ) than ( have been placed so far. Every string built under these two rules is valid, so no time goes into strings that would fail later.

Brute force: Generate all 2^(2n) strings of brackets and keep the balanced ones, which takes O(2^(2n) * n) time and throws almost all of them away.

Step by step

  1. 1Write backtrack(opened, closed), which grows a shared list of characters.
  2. 2When the string has 2 * n characters, save it and return.
  3. 3If opened < n, add (, recurse with opened + 1, then remove it.
  4. 4If closed < opened, add ), recurse with closed + 1, then remove it.

See the pattern move

The backtracking pattern on a small example. Step through it, or press play.

Code

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

        def backtrack(opened: int, closed: int) -> None:
            if len(current) == 2 * n:
                result.append("".join(current))
                return
            if opened < n:          # room for another "("
                current.append("(")
                backtrack(opened + 1, closed)
                current.pop()
            if closed < opened:     # a ")" must close an earlier "("
                current.append(")")
                backtrack(opened, closed + 1)
                current.pop()

        backtrack(0, 0)
        return result

Complexity

Time

O(4^n / sqrt(n))

Space

O(n)

The number of valid strings is the n-th Catalan number, about 4^n / (n * sqrt(n)), and each one takes O(n) to build; the recursion holds one string of length 2n.

Watch out for

  • Allowing ) whenever fewer than n have been used, which builds strings like ())( that close more than they opened.
  • Building every string first and checking validity only at the end, which explores far more strings than needed.

Follow-up questions

How many strings will there be?

The n-th Catalan number: 1, 2, 5, 14, 42 for n = 1 to 5. It grows roughly like 4^n.

How would you check whether one given string is valid?

Scan it once with a counter that goes up for ( and down for ). It is valid when the counter never drops below 0 and ends at 0.

In Hinglish

Open bracket tab tak lagao jab tak n se kam lage hain, aur close bracket sirf tab jab band karne ke liye koi open bracket baaki ho. In do rules se har string valid hi banegi.

Related problems