Examples
Write mostFrequentChar so that the following cases hold.
- Input
mostFrequentChar("javascript")Output"a" - Input
mostFrequentChar("aabbb")Output"b" - Input
mostFrequentChar("x")Output"x"
1 more hidden test cases - 4 in total will be graded.
Answer
js
function mostFrequentChar(str) {
const count = {};
let best = null;
for (const ch of str) {
count[ch] = (count[ch] || 0) + 1;
if (best === null || count[ch] > count[best]) best = ch;
}
return best;
}
mostFrequentChar("javascript"); // "a"
Updating best inside the loop keeps it single-pass. On a tie the character that reached the count first wins - state that convention out loud in an interview.
