Generate Parentheses

Build every well-formed string of n pairs of brackets by adding one bracket at a time.

Given a number n, return every string made of n opening brackets ( and n closing brackets ) that is well-formed. Well-formed means every ( is closed by a ) later in the string, and no ) appears without an open ( before it. The strings can come in any order.

Example 1
Input: n = 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
Example 2
Input: n = 1
Output: ["()"]
Solution

The Idea

Brackets in a sum on paper follow a rule you already know: (2 + 3) * (4 - 1) is fine, but )2 + 3( * 4 makes no sense. Each opening bracket needs a closing one after it. Here the numbers are gone and only the brackets are left, n pairs of them, and we want every correct way to line them up.

With one pair there is one answer, (), as Example 2 shows. With two pairs there are two: (()) and ()(). Four characters, each one either ( or ), can be written in 16 ways, and only these two pass. For three pairs there are 64 strings of six brackets and five answers, the ones in Example 1.

So writing every string and checking it afterwards throws away most of the work. Can we tell, while writing a string from left to right, that it has already gone wrong?

We can, by counting as we write: how many ( are placed so far, and how many ). Another ( may follow as long as fewer than n are placed. A ) may follow only when more ( than ) are placed, because then some bracket is still open and waiting to be closed.

Look at the picture below. It writes the strings for n = 2, starting from the box marked empty at the top. Each blue box offers two choices, add ( and add ), and each choice leads to a box one row down that holds the string so far.

The choice tree for n = 2. From the empty string each box tries add ( and add ). Dashed orange boxes are cut short, marked no ( left or nothing open to close. The two teal boxes at the bottom, (()) and ()(), are the answers.

The dashed orange boxes break one of the two counting rules, so the search stops there. From the empty box, add ) leads to ), marked nothing open to close. From ((, add ( would need a third opening bracket, marked no ( left. The blue and teal boxes are the strings actually written: eight, counting the empty one.

Follow the left side down. After (()) is found, the search goes back up, box by box, to ( and takes its other choice, add ), which leads to () and then to the second answer, ()(). Undoing the last bracket and trying the next choice from the box above is called backtracking.

Notice that every blue box in the picture leads down to a teal answer. The two counts cut a branch the moment it breaks a rule, so the search never wanders down a path that ends nowhere.

Solution Approach

Writing every string and keeping the balanced ones is the plain way, and it is slow. The faster way needs three decisions: which bracket may come next, how to take a bracket back, and when a string is complete.

Trying every string

Why not write all the strings of 2n brackets and keep the balanced ones? There are 22n of them, and each takes 2n steps to check. For n = 8 that means 65,536 strings to find the 1,430 answers.

Which bracket may come next

What decides the next character? The two counts: how many ( and how many ) are placed so far, kept in variables named open and close. A ( is allowed while open < n, and a ) is allowed while close < open. Both can hold at once, as at the box ( for n = 2, and then the search tries ( first and ) afterwards.

Why does a string that obeys both rules always end balanced? close never gets ahead of open, and open never passes n. When the string reaches 2n characters, the counts add up to 2n, so both must be exactly n.

Taking a bracket back

How does the search move between boxes? A method named build stands for one box. For each allowed choice it adds the bracket and calls itself, and that call handles the box one row down. When the call returns, the search is back at the box above.

All the calls share one StringBuilder, a string that can grow and shrink, named sb. Before a call, sb gets the new bracket appended. After it returns, deleteCharAt removes that bracket, so sb holds the string of the box above again, ready for the other choice.

When a string is complete

When does a branch stop with an answer? When sb holds 2n characters, all n pairs are used. The call copies the string with sb.toString() into the list of answers and returns. No separate check is needed, because the two counts already kept every step legal.

Java Solution

The method generateParenthesis works in these steps:

  1. First, create the list result for the answers and an empty StringBuilder named sb, and call build with open and close both at 0.
  2. Inside build, check the length of sb. If it is 2 * n, add a copy of it to result and return.
  3. If open < n, append '(', call build with open + 1, and then remove the last character with deleteCharAt.
  4. If close < open, do the same with ')' and close + 1.
  5. When the first call to build returns, every branch has been tried, and generateParenthesis returns result.

The main method runs Example 1, Example 2 and n = 2 from the picture, then prints how many answers there are for each n from 1 to 8.

Java
import java.util.ArrayList;
import java.util.List;

public class GenerateParentheses {

    public static List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        build(n, 0, 0, new StringBuilder(), result);
        return result;
    }

    private static void build(int n, int open, int close, StringBuilder sb, List<String> result) {
        if (sb.length() == 2 * n) {
            result.add(sb.toString());            // all n pairs placed: one answer
            return;
        }
        if (open < n) {                           // an opening bracket is still left
            sb.append('(');
            build(n, open + 1, close, sb, result);
            sb.deleteCharAt(sb.length() - 1);     // take it back before the next choice
        }
        if (close < open) {                       // some bracket is open and can be closed
            sb.append(')');
            build(n, open, close + 1, sb, result);
            sb.deleteCharAt(sb.length() - 1);
        }
    }

    public static void main(String[] args) {
        System.out.println(generateParenthesis(3));
        System.out.println(generateParenthesis(1));
        System.out.println(generateParenthesis(2));
        for (int n = 1; n <= 8; n++) {
            System.out.print(generateParenthesis(n).size() + (n < 8 ? " " : "\n"));
        }
    }
}

Running it prints:

Output
[((())), (()()), (())(), ()(()), ()()()]
[()]
[(()), ()()]
1 2 5 14 42 132 429 1430

The third line, [(()), ()()], holds the two teal boxes from the picture, in the same left-to-right order, because build tries ( before ). For the same reason, ((())) comes first on the line for n = 3.

The last line counts the answers for n from 1 to 8: 1, 2, 5, 14, 42, 132, 429 and 1430. The number of strings of 2n brackets grows much faster: 4, 16, 64 and so on up to 65,536. A separate run that counts the calls to build finds 22 calls for n = 3, against 64 strings for the plain way.

The second rule is easy to write wrongly as close < n. That version lets a ) come before its (. Run for n = 2, it returns six strings: (()), ()(), ())(, )((), )()( and ))((.

Complexity

The work depends on how many answers there are, because every box the search writes leads to at least one of them. For n pairs that number is called the n-th Catalan number, Cn = (2n)! / ((n + 1)! · n!), the values on the last line of the output.

  • Time: O(Cn · n), because each of the Cn answers ends a path of 2n + 1 calls and takes O(n) to copy, and Cn grows roughly like 4n / n1.5.
  • Space: O(n) besides the answers, because the calls nest at most 2n + 1 deep, one per bracket plus the first, and sb holds at most 2n characters.