JavaScript Algorithm: Alternating Characters

Erica N
Erica N
Mar 1, 2020 · 2 min read
Image for post
Image for post

For today’s algorithm, we are going to write a function called alternatingCharacters that will take one string, s as input.

You are given a string that only contains characters A and B. The goal of the function is to change the string so that the characters alternate and there are no matching adjacent characters. The function will return the number of matching adjacent character deletions it will take to have an A and B alternate-only string. Let’s look at an example:

let s = "ABAABBAB";

In our input string above there are some repeat adjacent characters. We will highlight the characters that we can remove to have an alternating string.

"ABAABBAB" --> remove A at position 3 and B at position 5

We remove the two characters so that we can have a string that doesn’t contain matching adjacent characters. The function will return 2.

Let’s turn this into code:

let deleteCount = 0;

Our deleteCount variable will hold the number of matching adjacent character deletions.

for(let i = 0; i < s.length; i++){
if(s[i] === s[i+1]){
deleteCount++;
}
}

Next, we iterate through the characters in our input string. We use the if-statement to check if the current character matches the character next to it in the string. If they match, the current character is unneeded so we increment the deleteCount variable.

After the loop ends, we return the deleteCount variable.

return deleteCount;

That’s the end of our short function. Here is the rest of the code:

function alternatingCharacters(s) {
let deleteCount = 0;
for(let i = 0; i < s.length; i++){
if(s[i] === s[i+1]){
deleteCount++;
}
}

return deleteCount;
}

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store