Computer >> Computer tutorials >  >> Programming >> Javascript

All ways of balancing n parenthesis in JavaScript


Problem

We are required to write a JavaScript function that takes in a number n. Our function should return an array showing all the ways of balancing n parenthesis.

For example, for n = 3, the output will be −

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

Example

Following is the code −

const res = [];
const buildcombination = (left, right, str) => {
   if (left === 0 && right === 0) {
      res.push(str);
   }
   if (left > 0) {
      buildcombination(left-1, right+1, str+"(");
   }
   if (right > 0) {
      buildcombination(left, right-1, str+")");
   }
}
buildcombination(3, 0, "");
console.log(res);

Output

Following is the console output −

[ '((()))', '(()())', '(())()', '()(())', '()()()' ]