All ways of balancing n parenthesis in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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 −

[ '((()))', '(()())', '(())()', '()(())', '()()()' ]
raja
Updated on 17-Apr-2021 12:07:54

Advertisements