Finding minimum deletions in string in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose we have a binary string like this −

const str = '001001';

We are required to write a JavaScript function that takes in one such string as the first and the only argument.

The function should then compute and return the number of minimum deletions required in the input so that no two adjacent numbers are the same.

For example, for the above string, the output should be −

const output = 2;

because if we delete '0' at index 0 and 3, the new string will be '0101' which is the longest desired string.

Example

The code for this will be −

 Live Demo

const str = '001001';
const minimumDeletions = (str = '') => {
   let count = 0;
   const { length } = str;
   for(let i = 0; i < length; i++){
      if (str[i] === str[i + 1]){
         count++;
      };
   }
   return count;
};
console.log(minimumDeletions(str));

Output

And the output in the console will be −

2
raja
Published on 24-Feb-2021 06:05:12
Advertisements