Algorithms and Data Structures Part III

Photo by Sven Brandsma on Unsplash

In this part I will be discussing a technique that is applicable to many other string related questions. Once again if you’re here before reading part II jump over HERE and give that and part I a read if you haven't seen those yet.

Okay so let's get into it…


For this problem you are given a string and asked to return the character that is most commonly used in the string.

e.g. maxChar(“adcccd”) === “c” || maxChar(“apple 11123”) === “1”

So once again we will start with an empty function…

Now we will declare a new variable, and it will be an empty object…

next we need to iterate over the source str and use that to build out our character map.

What this is saying is, for every character that we receive we will add an entry to our charMap and if an entry already exists there, then we will just add 1 to the number.

So now we have our character map built up we want to iterate over it to find the character that is used most frequently in a given string.

For this we will need two helper variables at the top of the function.

We will iterate through the character map. If we find a character that has more uses than max we will set max equal to the new value, and we will set maxChar equal to the character that is responsible for that number of uses.

Below is our loop to iterate through our character map…

Notice the for in loop instead of for of loop. For of is used for iterating through an array or a string or any kind of iterable object but in this case we are iterating through an actual object or a collection of key, value pairs so we use the for in loop.

With this loop we will know which character has the most uses and that will be assigned to maxChar so the last thing we need to do is just…

and that will give us our answer. Below is the full function…

Thanks for reading and look out for part IV where I will be discussing the famous FIZZBUZZ problem.

See ya next week!!

Learning to code, one day at a time.

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