Was it helpful?

Question

JavaScript: Balancing parentheses

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Given a string that consists of only two types of characters: "(" and ")". We are required to write a function that takes in one such string and balances the parentheses by inserting either a "(" or a ")" as many times as necessary.

The function should then return the minimum number of insertions made in the string to balance it. For example −

If the string is −

const str = '()))';

Then the output should be 2, because by prepending '((', we can balance the string.

Example

Following is the code −

const str = '()))';
const balanceParanthesis = str => {
   let paren = [];
   for (let i = 0; i < str.length; i++) {
      if (str[i] === "(") {
         paren.push(str[i]);
      } else if (str[i] === ")") {
         if (paren[paren.length - 1] === "("){
            paren.pop();
         }else {
            paren.push("#");
         };
      };
   }
   return paren.length;
}
console.log(balanceParanthesis(str));

Output

This will produce the following output on console −

2
raja
Published on 01-Oct-2020 14:10:21
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top