Algorithms and Data Structures Part III

MaxChar

Brian Butterly
3 min readFeb 18, 2021
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…

MaxChar

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…

function maxChar(str) {}

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

function maxChar(str) {
const charMap = {}
}

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…

return maxChar

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!!

--

--