Finding the balance of brackets in JavaScript

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

The code for this will be −

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

The output in the console will be −

2
raja
Published on 24-Oct-2020 11:57:59
Advertisements