Removing 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: 17-Apr-2021

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements