← Whiteboard questions

Generate Parentheses

List every balanced arrangement of n pairs of brackets

DSA, Medium, Stack

Which structure or algorithm, and what does it cost.

Given a whole number n, build every string that uses exactly n pairs of round brackets and is balanced. Balanced means every ( is closed by a later ), and no ) comes before the ( it closes. Return all such strings, each one once, in any order. For n = 0 the only string is the empty one.

Examples

Input n = 2
Output ["(())", "()()"]
Why one pair nested in the other, or two pairs side by side. The string "())(" is not balanced, because its second bracket closes nothing.
Input n = 4
Output ["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]
Why there are 14 balanced strings. Each starts with an opening bracket, and no prefix closes more brackets than it has opened.
Input n = 0
Output [""]
Why there are no pairs to place, so the only string is the empty one.

Constraints

Your answer must contain

Target Aim for about n times the number of answers in time, by building only prefixes that can still end balanced.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Build one string, adding a bracket at a time. At each step, ask which choices could still lead to a balanced string.

Hint 2 the approach

Which counts tell you that a closing bracket is safe to add? Which count tells you that an opening one is? Think about what to track as you build.

Hint 3 the key step

Carry two counts as you recurse: brackets opened and brackets closed. Write one condition on these counts for adding each kind of bracket. When is the string complete?

Walkthrough

Full walkthrough brute force to best

Brute force

Try every string of 2n brackets, which is 4^n strings, and keep the balanced ones by checking each with a running count. For n = 9 that is 262,144 strings to find 4,862 answers, so 98 of every 100 strings are built and thrown away, and each extra pair multiplies the work by 4. Most strings are not balanced, so most of the work is wasted.

Best method

Build the string one bracket at a time and take only steps that can still end balanced. Track how many opening brackets and how many closing brackets the string has. An opening bracket is allowed while fewer than n were used. A closing bracket is allowed only while the closing count is below the opening count, so it never closes something that is not open. When the string reaches length 2n, both counts are n and no prefix closed too much, so it is balanced. A step that is refused could never lead to a balanced string, so no answer is missed. Trying the opening bracket first lists the answers in a fixed order.

Hand trace

Run on n = 2. Start with the empty string, opened 0, closed 0. Add an opening bracket: "(" (1, 0). Add another: "((" (2, 0). Opening is no longer allowed. Add a closing bracket: "(()" (2, 1). Add another: "(())" has length 4, so save it. Go back to "(" (1, 0). Opening was tried, so try closing: "()" (1, 1). Closing is not allowed here because closed equals opened. Add an opening bracket: "()(" (2, 1). Add a closing bracket: "()()" has length 4, so save it. The result is ["(())", "()()"].

Code

def generate_parentheses(n):
    result = []
    def build(current, opened, closed):
        if len(current) == 2 * n:
            result.append(current)
            return
        if opened < n:
            build(current + "(", opened + 1, closed)
        if closed < opened:
            build(current + ")", opened, closed + 1)
    build("", 0, 0)
    return result

Time and memory

Time is about n times the number of answers, because every partial string leads to at least one answer and each string copy costs up to n. The number of answers is the Catalan number, about 4^n divided by n^1.5. Memory is O(n) for the recursion depth, not counting the output.

Common mistakes

  • Allowing a closing bracket whenever the string has room. Check that closed is below opened, or you build strings such as "())(".
  • Checking balance only at the end. That brings back the 4^n search and throws the pruning away.
  • Forgetting n = 0. The answer is a list with one empty string, not an empty list.
  • Building the string in one shared list and not removing the bracket after each recursive call. Every append needs its own pop, or later branches start from the wrong string.

Related problems

More Stack problems
Generate Parentheses: hints, walkthrough and Python solution