Menu
CoddyTech

Generate Parentheses

A string of parentheses is well formed when, read from left to right, the count of ) never gets ahead of the count of (, and the two counts are equal at the end. So (())() is well formed, while ())( is not: its third character closes a pair that was never opened.

Given an integer n, return every well-formed string of n opening and n closing parentheses, sorted in lexicographic order, where ( comes before ).

Function

generateParenthesis(n: integer) → string-array
ninteger
the number of pairs of parentheses
Returnsstring-array
every well-formed string of n pairs, in lexicographic order

Constraints

  • 1 ≤ n ≤ 8
  • For n = 8 the answer holds 1,430 strings.

Examples

Input
n = 3
Output
["((()))", "(()())", "(())()", "()(())", "()()()"]
Explanation
Three pairs make five well-formed strings. ((())) opens all three first, so it sorts first; ()()() closes each pair at once and comes last.
challenge icon

Follow-up

Can you count the well-formed strings for n pairs without generating them?

Reset code
def generateParenthesis(n):
    # Write code here

Test #1

Test #2

Argument

n = 3

Expected Output

["((()))", "(()())", "(())()", "()(())", "()()()"]