Generate Parentheses

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write generateParens(n): return an array of every balanced string of n opening and n closing round brackets, where n is a whole number from 1 to 8. A string is balanced when, reading from the left, there are never more closing brackets than opening ones so far, and the counts match at the end. The strings can come in any order, each once. For example, generateParens(3) could return ["((()))", "(()())", "(())()", "()(())", "()()()"]. Grow the strings a bracket at a time, adding a closing one only while some opening one is still unmatched.

Your code must pass

  • Lists the 5 strings for n = 3
  • Handles n = 1 and n = 2
  • Lists all 1,430 strings for n = 8