Generate Parentheses

35 min · generateParenthesis()

A closing parenthesis can't pay a debt that hasn't been opened yet. That one rule lets you reject bad strings long before they're finished.

For an integer n, build every string that uses exactly n opening parentheses and n closing parentheses in a valid arrangement. A string is valid when every opening parenthesis has a later closing partner and no prefix closes more pairs than it opens.

Return the valid strings in any order, with no duplicates.

Constraints

  • 1 <= n <= 8
  • The largest case has 1,430 valid strings.

Hints

A truthful first draft

You can generate every length-2 × n string made from ( and ), then scan each one with a balance counter. How many candidates does that create?

Protect every prefix

Track how many opening and closing parentheses you've placed. You may add ( while the opening count is below n; when is adding ) safe?

Two gates

Add a closing parenthesis only when close < open. Once both counts reach n, the current path is a complete answer and needs no separate validity check.

Follow-up

Could you compute how many answers exist for a given n without constructing any of the strings?

Visible cases

Examples

Example 1

ready
Input
n = 1
Expected
[
  "()"
]
Why
one pair has only one valid arrangement

Example 2

ready
Input
n = 3
Expected
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
Why
all five strings keep every prefix balanced

Example 3

ready
Input
n = 2
Expected
[
  "(())",
  "()()"
]
Why
the pairs may nest or sit side by side

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite