Algorithm Problem: Find the MaxChar
Like other algorithm problems this is another problem which is a pretty common in interviews. Also, It might look hard looking at the problem, but you just need to know a few tricks to become familiar with it.
What is a MaxChar problem? First of all, in a MaxChar problem Char means “character”. In a MaxChar problem you will have to return the character that is most commonly used in the string.
Example:
MaxChar(“abcccccd”) === “c”
MaxChar(“apple 12311111”) === “1”
For all the questions where to have to find the max characters or compare characters in two strings you can always use the below technique.
We are going to take the string in, turn it into an object, where the keys of the object are the characters of the string and the values are the number of times the characters has been found.
Example:
First, we will iterate over the string and add that character into a new object called charMap. We will use the for of function to iterate over the string, then for every character we find we will add a property to charMap. If we find the character first time, then we will set its value to 1 otherwise we will increment the character by 1. To do that we will use an if function. At the we can print out chars to see the object. Now we need to find the max character. To do that we will need to iterate over the charMap. We also need to have two helper variables max=0 and maxChar=’ ‘. We will iterate over the string using the for in loop. If we ever find a character that have more usage then we will set max = that new value and maxChar = that character. At the end we just need to return maxChar. See the example below: