DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 75

The task is to implement a function that returns the most frequently occuring character.

The boilerplate code

function count(str: string): string | string[] {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

First, count how many times each chracter appears

const freq: Record<string,number> = {}

for (let char of str) {
    freq[char] = (freq[char] || 0) + 1;
  }
Enter fullscreen mode Exit fullscreen mode

Find the character with the highest count.

let max = 0;
  for (let char in freq) {
    if (freq[char] > max) {
      max = freq[char];
    }
  }
Enter fullscreen mode Exit fullscreen mode

Collect all the characters with the highest count

const result = Object.keys(freq).filter(char => freq[char] === max);
Enter fullscreen mode Exit fullscreen mode

If only one character has the highest count, return it as a string. If there are more than one return them as an array.

 return result.length === 1 ? result[0] : result;
Enter fullscreen mode Exit fullscreen mode

The final code

function count(str: string): string | string[] {
  // your code here
  const freq: Record<string, number> = {}

  for(let char of str) {
    freq[char] = (freq[char] || 0) + 1; 
  }

  let max = 0; 
  for(let char in freq) {
    if(freq[char] > max) {
      max = freq[char]
    }
  }
  const result = Object.keys(freq).filter(char => freq[char] === max);

  return result.length === 1 ? result[0] : result;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)