iq.lab
Python starts when a code cell comes near or you run one
mediumBacktracking target 25 min

Generate balanced parentheses

You get a whole number n. Return every string made of exactly n opening brackets ( and n closing brackets ) that is balanced: read left to right, every ) closes an earlier ( that is still open, and no ( is left open at the end.

So (()) and ()() are balanced. )( is not, because its ) has nothing to close, and (() is not, because one ( is never closed.

Return a list of strings that holds each balanced string exactly once, in any order.

Example 1
Inputn = 2Output["(())", "()()"]

Two of each bracket can be arranged in 6 ways, and only these 2 are balanced. For example, ())( fails at its third character: a ) with nothing open.

Example 2
Inputn = 3Output["((()))", "(()())", "(())()", "()(())", "()()()"]

5 of the 20 arrangements of three of each bracket are balanced.

Example 3
Inputn = 1Output["()"]

)( uses the same two brackets, but its ) comes before any (.

Constraints
  • 1 ≤ n ≤ 12

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.