0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Most Frequent Character

Use a JavaScript function that counts each character's occurrences with an object, then find the character with the highest count; for example, function mostFrequentChar(str) { const counts = {}; for (const char of str) { counts[char] = (counts[char] || 0) + 1; } let maxChar = ''; let maxCount = 0; for (const char in counts) { if (counts[char] > maxCount) { maxCount = counts[char]; maxChar = char; } } return maxChar; }
📋

Examples

Inputhello
Outputl
Inputjavascript
Outputa
Inputaabbccddeeff
Outputa
🧠

How to Think About It

To find the most frequent character, first count how many times each character appears by going through the string one by one. Then, look through these counts to find which character has the highest number. Return that character as the result.
📐

Algorithm

1
Create an empty object to store character counts.
2
Loop through each character in the input string.
3
For each character, increase its count in the object by one.
4
After counting, find the character with the highest count.
5
Return the character that appears most frequently.
💻

Code

javascript
function mostFrequentChar(str) {
  const counts = {};
  for (const char of str) {
    counts[char] = (counts[char] || 0) + 1;
  }
  let maxChar = '';
  let maxCount = 0;
  for (const char in counts) {
    if (counts[char] > maxCount) {
      maxCount = counts[char];
      maxChar = char;
    }
  }
  return maxChar;
}

console.log(mostFrequentChar('hello'));
Output
l
🔍

Dry Run

Let's trace the input 'hello' through the code

1

Initialize counts object

counts = {}

2

Count characters

After looping: counts = { h: 1, e: 1, l: 2, o: 1 }

3

Find max character

maxChar = '', maxCount = 0 Check 'h': count=1 > 0, maxChar='h', maxCount=1 Check 'e': count=1 == maxCount, no change Check 'l': count=2 > 1, maxChar='l', maxCount=2 Check 'o': count=1 < maxCount, no change

4

Return result

Return 'l'

CharacterCountMaxCharMaxCount
h1h1
e1h1
l2l2
o1l2
💡

Why This Works

Step 1: Counting characters

The code uses an object to keep track of how many times each character appears by adding 1 each time it sees the character.

Step 2: Finding the maximum

It then checks all counts to find the character with the highest number, updating the max when it finds a bigger count.

Step 3: Returning the result

Finally, it returns the character that appeared the most times as the answer.

🔄

Alternative Approaches

Using Map instead of object
javascript
function mostFrequentChar(str) {
  const counts = new Map();
  for (const char of str) {
    counts.set(char, (counts.get(char) || 0) + 1);
  }
  let maxChar = '';
  let maxCount = 0;
  for (const [char, count] of counts) {
    if (count > maxCount) {
      maxCount = count;
      maxChar = char;
    }
  }
  return maxChar;
}
console.log(mostFrequentChar('hello'));
Map can be clearer and safer for keys but slightly more complex syntax.
Using Array reduce
javascript
function mostFrequentChar(str) {
  const counts = [...str].reduce((acc, char) => {
    acc[char] = (acc[char] || 0) + 1;
    return acc;
  }, {});
  return Object.keys(counts).reduce((a, b) => counts[a] > counts[b] ? a : b);
}
console.log(mostFrequentChar('hello'));
Using reduce is concise but may be harder for beginners to read.

Complexity: O(n) time, O(k) space

Time Complexity

The program loops through the string once to count characters, which takes O(n) time where n is string length. Then it loops through the counts object which has at most k keys (unique chars), so total is O(n + k), simplified to O(n).

Space Complexity

It uses extra space to store counts for each unique character, so space is O(k), where k is number of unique characters.

Which Approach is Fastest?

Using an object or Map both have similar performance. The reduce method is concise but not faster. The main cost is counting characters once.

ApproachTimeSpaceBest For
Object countingO(n)O(k)Simple and fast for most cases
Map countingO(n)O(k)Better key handling, slightly more complex
Reduce methodO(n)O(k)Concise code, less beginner-friendly
💡
Use an object or Map to count characters quickly and then find the max count.
⚠️
Forgetting to initialize counts or not updating counts correctly causes wrong results.