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
}
First, count how many times each chracter appears
const freq: Record<string,number> = {}
for (let char of str) {
freq[char] = (freq[char] || 0) + 1;
}
Find the character with the highest count.
let max = 0;
for (let char in freq) {
if (freq[char] > max) {
max = freq[char];
}
}
Collect all the characters with the highest count
const result = Object.keys(freq).filter(char => freq[char] === max);
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;
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;
}
That's all folks!
Top comments (0)