Solving MAX CHARACTER PROBLEM

Bryam Vicente
3 min readApr 6, 2021

--

For this blog I’ll be solving another popular algorithm problem, Max Character. Note that this problem will be solved in JavaScript!

The question is asking us to create a function that returns the character that’s used the most in a string. Judging from the examples on lines 6 and 7, both the input and output should be strings. My solution for this problem has a time complexity of O(n)!

Using arrays would be a great way to solve this problem, but I’m going to use hash tables just to show another way of solving this problem. I created a variable charHash that represents the empty object that I’m creating. I created another variable max, which represents the amount of times a specific character is used inside a string. I also created a variable maxChar, that represents the string that will be returned. This is what the code looks like at the moment:

The next step is to iterate over str to check each character inside the string. For this task, I’ll be using a For of statement!

The logic inside the For of loop is only half of what we’re really trying to do. We need to create a conditional that checks if charHash[character] exists. If it does exist, then continue to increment and if it’s false then I should set charHash equal to 1. Here’s what the code looks like right now:

Like mentioned before, this is only half of what we want the function to do. Here we’re just checking each character inside the string. We now have to iterate over the actual object to get the output that we need.

Let’s go over lines 24-29 step by step! On line 24, I used a For in loop that’s going to iterate over the object charHash. This is what charHash looks like when using ”sttring”:

Now that we know what our object looks like, we then have to create some logic that can return the letter t since it’s the character that appears the most. Lines 25–26 are stating that if the value of the keys is greater than the variable max (which is currently 0), then take max and set it equal to the value (charHash[character]). Line 27 is then taking the variable that I created in the beginning maxChar, and setting that equal to the key (character). The last step is having to return the key that has the bigger value, which in my case is t. Here’s the full solution:

Please feel free to reach out or leave a comment on this blog if there are better solutions for this problem! For more info on for of and for in statements, and hash tables make sure to check out the resources section below!

Resources:

--

--

No responses yet