JavaScript Coding Challenge #5

Hello campers!

Here is my fifth coding challenge on medium called Alternating Characters. It is from HackerRank.


Let me know what you think of it! :smiley:

Looks good, I love how you used the Array.prototype.reduce method :slight_smile:

I just solved it and I remembered there’s a concept in RegExp called back-references which allow you to refer back to previously captured groups, so I thought it would be fairly easy to extract those groups of letters that are consecutive:

const nrOfDeletions = str => {
  let repeated = str.match(/(\[a-z])\1+/gi)

  return repeated.join('').length - repeated.length
}

All I do is take the overall count of letters that are consecutive and subtract the length of the groups array (the repeated variable) which is logically equivalent as subtracting 1 character to each group of repeated letters.

Imagine a string like “abbbaalotteec”, the number of deletions is 5 and my regex would match the following:

['bbb', 'aa', 'tt', 'ee']

The the number of deletions should be the sum of: (3-1) + (2-1) + (2-1) + (2-1) because we want to keep the first letter and get rid of the consecutive rest, that’s why I subtract one to each group.

Now on the Regex, the magic happens with: \1 which is just a reference to the first capturing group, which captures a character inside the range of a-z (both uppercase and lowercase) because of the i (case-insensitive) flag.

1 Like

Lovely @luishendrix92 ! I still need to learn more about regex! :slight_smile:
I love your approach!