Menu
CoddyTech

Generate Parentheses

A string of parentheses is well formed when, read from left to right, the number of ) never gets ahead of the number 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.

You get an integer n. Return every well-formed string made 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 can be arranged in five well-formed ways. ((())) opens all three before closing any, and since ( sorts first it leads the list; ()()() closes each pair at once and comes last.

lock icon+10 hidden tests on Submit

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 cases

Case 1

Case 2

Input

n = 3

Expected

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