Placing integers at correct index in JavaScript


Problem

We are required to write a JavaScript function that takes in a string, str, which consists of only ‘[‘ or ‘]’. 

Our function is supposed to add the minimum number of square brackets ( '[' or ']', and in any positions ) so that the resulting bracket combination string is valid. And lastly, we should return the smallest number of brackets added.

For example, if the input to the function is

Input

const str = '[]]';

Output

const output = 1;

Output Explanation

Because, if we add ‘[‘ to the starting, the string will be balanced.

Example

const findAdditions = (str = '') => {
   let left = 0
   let right = 0
   for (let i = 0; i < str.length; i++) {
      if (str[i] === '[') {
         left += 1
      } else if (str[i] === ']') {
         if (left > 0) {
            left -= 1
         } else {
            right += 1
         }
      }
   }
   return left + right;
};
console.log(findAdditions(str));

Output

1

Updated on: 23-Apr-2021

31 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements