Generate Parentheses

Pattern: Recursion trees

medium

Build the string one bracket at a time. An opening bracket is allowed while fewer than n are used; a closing bracket only while it has an open one to match. Every leaf of that tree is a valid string.

The problem

Given n, return every string of n pairs of brackets that is well formed: each opening bracket is closed later, in the right order. For example, n = 3 gives ((())), (()()), (())(), ()(()) and ()()().

The function name generateParenthesis matches LeetCode. Use the link above for the exact statement and limits. LeetCode accepts any order; this guide's tests compare the answers after sorting them.

Think first

  • At any point, when may you add (? When may you add )?
  • How many characters does each answer have?
  • Why is checking only at the end wasteful?

Hints

    Brute force, and why it fails

    Generate all 2^(2n) strings of brackets and keep the balanced ones: O(2^(2n) × n). The two rules only build valid prefixes, so every leaf is an answer, and the work is close to the size of the output.

    The key insight

    A prefix stays fixable exactly when it never has more ) than ( and never more than n of (. Enforcing that at every step prunes every dead branch at once.

    Dry run

    cur
    open0
    close0

    n = 2. Start with an empty string, open = 0 and close = 0.

    Step 1 of 4

    The plan

    function build(cur, open, close):
        if len(cur) == 2n: record cur; return
        if open < n: build(cur + "(", open + 1, close)
        if close < open: build(cur + ")", open, close + 1)
    build("", 0, 0)
    

    Complexity

    Time
    O(4ⁿ / √n)
    Space
    O(n)

    The number of answers is the n-th Catalan number, about 4ⁿ / (n^1.5), and each takes O(n) to write. The recursion is 2n deep.

    Edge cases

    • n = 1: just ().
    • Larger n grows quickly: n = 8 has 1430 answers.
    • No answer is ever repeated, since each is built along one path.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> out = new ArrayList<>();
            build(new StringBuilder(), 0, 0, n, out);
            return out;
        }
    
        private void build(StringBuilder cur, int open, int close, int n, List<String> out) {
            if (cur.length() == 2 * n) { out.add(cur.toString()); return; }   // a full, valid string
            if (open < n) {                                  // we may still open a bracket
                cur.append('('); build(cur, open + 1, close, n, out); cur.deleteCharAt(cur.length() - 1);
            }
            if (close < open) {                              // we may close only what is open
                cur.append(')'); build(cur, open, close + 1, n, out); cur.deleteCharAt(cur.length() - 1);
            }
        }
    }

    C++

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> out;
            string cur;
            build(cur, 0, 0, n, out);
            return out;
        }
    
        void build(string& cur, int open, int close, int n, vector<string>& out) {
            if (static_cast<int>(cur.size()) == 2 * n) { out.push_back(cur); return; }   // a full, valid string
            if (open < n) { cur.push_back('('); build(cur, open + 1, close, n, out); cur.pop_back(); }   // may still open
            if (close < open) { cur.push_back(')'); build(cur, open, close + 1, n, out); cur.pop_back(); }   // close what is open
        }
    };

    Python

    class Solution:
        def generateParenthesis(self, n: int) -> list[str]:
            out = []
    
            def build(cur: list, opened: int, closed: int) -> None:
                if len(cur) == 2 * n:
                    out.append("".join(cur))        # a full, valid string
                    return
                if opened < n:                      # we may still open a bracket
                    cur.append("(")
                    build(cur, opened + 1, closed)
                    cur.pop()
                if closed < opened:                 # we may close only what is open
                    cur.append(")")
                    build(cur, opened, closed + 1)
                    cur.pop()
    
            build([], 0, 0)
            return out

    Common mistakes

    • Allowing ) when close == open, which creates invalid prefixes.
    • Forgetting to undo the last bracket when sharing one buffer.
    • Generating everything and filtering at the end.

    Similar problems