DEV Community

Tadea Simunovic
Tadea Simunovic

Posted on

How to find the maximum character in a string and how many times it appeared

I will be writing a series of blogs on the theme of algorithms and data structures.
The reason for this is that I'm preparing for upcoming interviews and wanted to share with you some of the most common challenges and how to resolve them.

Challenge
Given a string, return the character that is most commonly used in the string.
Common string Q's to use this solution
What is the most common character in a string?
Does the string have any repeated characters in it?
Does string A have the same characters as string B(is it an anagram?)?

How to start? For example, if you have a string "Hello World", what you will do is take that string and convert it to a new object, where the keys for an object are characters from the string and values are the number of times that characters are found.
Alt Text

Let's start!
Alt Text
We will declare a new variable and it will be an empty object line 14
Next, we will iterate over a string object and use it to store it in a new variable we just created. We will use for..of loop so for each character in a string we receive, we will add to charMap object. So if the object already exists we will increment value by 1 line 17-18, else if not then we will set the initial value to 1 line 19-20
If you run this file and open up a console, you should see this output.
Alt Text

Next is to iterate over the object to see what character appeared most of the time in a given string.

We will declare two helper methods on top of the function.let max = 0 and let maxChar = ''

If we find a character that has more uses then our variable max then we will set max equal to that new value and we'll set maxChar to a character that was responsible for that number of uses.
So, in other words, the first time we iterate through the "Hello World" object right here we would look at the key-value pair of H and 1 since 1 is greater than the initial variable of max, we would say this must be a new maximum that we found, so we would set max to 1, and then maxChar would be set to the key at that location which is H, we would then go onto the next value.

Since we will iterate over the object we need to use for..in loop since we are going through an object, not a string or array, like before.

Alt Text

On line 25 look at each character for charMap, then on line 26 if the charMap at this particular character is greater than our max we're going to update both, the max number and the max character. So on line 27 max will become charMap[chars] and maxChar will become chars.

On line 25when we iterate with a for in loop chars is assigned to the keys inside that object, so this is not the values it is the key.

Now after we run the loop we should then know which character is the greatest number of uses it will be assigned to maxChar.

In this case, console.log(maxChar) will return 'l'

Top comments (0)