# How to resolve the Max Char Algorithm

Photo belongs to [Drew Beamer](https://unsplash.com/es/@dbeamer_jpg?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash) in [Unsplash](https://unsplash.com/es/fotos/you-didnt-come-this-far-to-only-come-this-far-lighted-text-Vc1pJfvoQvY?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash)

Welcome back, algorithm enthusiasts! I hope you’ve been studying hard.

Last week, we counted the [vowels in a string](https://medium.com/@rubenosmaralvarado/vowels-count-algorithm-2fd24ba72cd4) and learned how to identify each character. This time, we’re going further by finding the max character in a string. This is another common challenge frequently encountered in technical interviews.

### Problem Statement

> *Given a string, return the character that is most commonly used in the string.*

Building on our [previous lesson](https://medium.com/@rubenosmaralvarado/vowels-count-algorithm-2fd24ba72cd4), we’ll apply what we learned about looping through strings and character identification. Previously, we counted specific characters from a predefined list. Now, we’re advancing to find the most frequent character in a string. While the underlying concept is similar, this challenge is more complex as it requires mapping and tracking each unique character’s frequency rather than just counting specific ones.

As usual, the problem statement gives us the input and the desired output: a string, and the character with the highest frequency.

### Algorithm to solve it

* First of all, we need to declare 3 variables: a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) for store each char and his occurrencies, a string to store the most frequent char and finally, an integer to store the max count of all.
    

```typescript
const charMap = new Map<string, number>();
let maxChar = '';
let maxCount = 0;
```

We could use a simple object to map characters, but `Maps` offer several advantages over objects. While objects work fine for basic needs, a more complex solution will benefit from using the Map object.

* Next, iterate through each character in our string using the good old [for…of](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Statements/for...of) loop
    

```typescript
for (const char of str) {}
```

* Now, for each iteration, we need to update our character count. Create a `count` const to store each character's occurrence. We'll access the character key in our `charMap`. If the character exists, we increment its count by one. If not, we start with zero and increment by one. This can be done with a one liner.
    

```typescript
const count = (charMap.get(char) ?? 0) + 1;
```

* Then, update the `charMap` with the character and its count. This will either override the existing value with the new count or create a new entry with the character and initialize its count to one.
    

```typescript
charMap.set(char, count);
```

* However, we still have more to do. Because we need to find the `maxChar`, and we just checked the char occurrence. So, we need to check if the current `count`, for this char in the iteration is higher than the `maxCount`
    

```typescript
if (count > maxCount)
```

* If it’s higher, update the `maxCount` variable with the current count and the `maxChar` variable with the current character. This ensures we always track the character with the highest occurrence as we progress through the string. Easy, right?
    

```typescript
maxCount = count;
maxChar = char;
```

* If the `count` is lower than `maxCount`, the loop continues to the next iteration while our `maxCount` and `maxChar` variables remain unchanged. Finally, after we've looped through the entire string, we have our `maxChar` ready to return.
    

```typescript
return maxChar;
```

### Typescript implementation

Here’s the complete solution implemented in TypeScript:

```tsx
export function maxChar(str: string): string {
    const charMap = new Map<string, number>();
    let maxChar = '';
    let maxCount = 0;

    for (const char of str) {
        const count = (charMap.get(char) ?? 0) + 1;
        charMap.set(char, count);
        if (count > maxCount) {
            maxCount = count;
            maxChar = char;
        }
    }

    return maxChar;
}
```

### Conclusion

In this post, we’ve tackled another fundamental algorithmic challenge: finding the most frequently occurring character in a string. This algorithm builds upon our previous knowledge of string manipulation and introduces the concept of frequency mapping using JavaScript’s Map object.

The solution we’ve implemented is both efficient and straightforward, with a [time complexity](https://medium.com/@rubenosmaralvarado/a-travel-between-space-and-time-complexity-725c7a989176) of O(n) where `n` is the length of the input string. We only need to traverse the string once, updating our character counts and tracking the maximum as we go.

Beyond technical interviews, this pattern of finding the most frequent element appears in various real-world applications, from text analysis to data compression algorithms. Understanding this concept will serve you well in your programming journey.

Next week, we’ll take a break from algorithms to explore the Hash Table data structure, which we’ve already utilized in this exercise.

And remember, you can check this and another algorithms in my repo: [https://github.com/RubenOAlvarado/algorithms](https://github.com/RubenOAlvarado/algorithms)

Until then, happy coding!
