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 −

 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 −

[ '((()))', '(()())', '(())()', '()(())', '()()()' ]
Updated on: 2021-04-17T12:07:54+05:30

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements