Skip to content
AI360Xpert
Beta
Difficulty: MediumStack

Generate Parentheses

Problem in Plain English

Given n pairs of parentheses, generate every string of n open and n close brackets that is correctly balanced. Return all distinct well-formed combinations in any order.

Problem Statement

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

A string is well-formed when every open bracket ( is eventually closed by a matching ), and at no point while scanning left to right do the closing brackets outnumber the opening ones. The count of valid strings is the n-th Catalan number, so n = 3 yields exactly 5 combinations.

Constraints

  • 1 <= n <= 8

Examples

Example 1

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

These are all 5 well-formed strings that use exactly 3 open and 3 close brackets.

Example 2

Input
n = 1
Output
["()"]

With a single pair there is only one balanced arrangement.

Example 3

Input
n = 2
Output
["(())","()()"]

Two pairs may nest or sit side by side. )(() and ())( have equal totals but close an unfinished pair that does not exist; ((() leaves openers unmatched. Thus only (()) and ()() qualify.

Intuition

An opening bracket creates one unfinished pair; a closing bracket finishes the most recent unfinished pair. Track the number of unfinished pairs as a balance. For n = 3, ((())) has balances 1, 2, 3, 2, 1, 0, so every close has an opener and nothing remains unfinished. A balanced total alone is insufficient: ())(() reaches -1 before recovering. Generate choices from left to right and reject a close as soon as it would make that balance negative.

Approaches

Enumerate All Strings

Solution Details

Reveal Enumerate All Strings: intuition, complexity, and code

Hints

Hint 1
A closing bracket is only legal when fewer closes than opens have been placed so far.
Hint 2
Think of building the answer one character at a time while tracking two counters, open and close.
Hint 3
Recurse with open + 1 when open is below n and with close + 1 when close is below open, recording the string once its length reaches 2n.

Edge Cases

  • n = 1 yields exactly one combination, so the close branch is taken exactly once per path.
  • Strings that close before opening, such as ")(", must be discarded the moment the balance goes negative.
  • The upper bound n = 8 produces 1430 strings, which fits easily in memory but already shows the Catalan growth.

Common Mistakes and Interview Tips

  • Allowing ) when close equals open, which builds strings like "())(()" that can never recover.
  • Checking only the final counts and missing prefixes where closes temporarily outnumber opens.
  • Forgetting the base case at length 2n, which lets the recursion append brackets forever.
  • Saving a mutable working buffer instead of a fresh string, or forgetting a pop after a recursive child, corrupts answers as later branches edit the same buffer. Java uses a fixed buffer: only slots before pos are part of the active prefix, and every deeper slot is overwritten before a leaf.
  • Calling the whole search linear because only valid strings are explored: n = 8 still returns 1430 distinct strings of length 16. Output storage cannot be omitted from a total-space claim.

Key Takeaway

Backtracking keeps a partial answer valid at every step and restores shared working storage when a choice returns. Pruning removes impossible prefixes, while the number and size of requested answers still impose exponential output work.