Remove Letters to Make Adjacent Pairs Different Using JavaScript



Problem

We are required to write a JavaScript function that takes in a string that contains only ‘A’, ‘B’ and ‘C’. Our function should find the minimum number of characters needed to be removed from the string so that the characters in each pair of adjacent characters are different.

Example

Following is the code −

 Live Demo

const str = "ABBABCCABAA";
const removeLetters = (str = '') => {
   const arr = str.split('')
   let count = 0
   for (let i = 0; i < arr.length; i++) {
      if (arr[i] === arr[i + 1]) {
         count += 1
         arr.splice(i, 1)
         i -= 1
      }
   }
   return count
}
console.log(removeLetters(str));

Output

3
Updated on: 2021-04-17T12:49:04+05:30

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements