Return the character that occurs most often in a string (e.g. "success" -> "s").
Build a frequency map in one pass, then scan the map for the entry with the highest count (tracking a running max). Ties can be broken by first occurrence or by natural order — clarify. O(n).
public static char mostFrequent(String s) {
Map<Character,Integer> m = new LinkedHashMap<>();
for (char c : s.toCharArray()) m.merge(c, 1, Integer::sum);
char best = s.charAt(0); int max = 0;
for (var e : m.entrySet()) if (e.getValue() > max) { max = e.getValue(); best = e.getKey(); }
return best;
}function mostFrequent(s) {
const m = {};
let best = s[0], max = 0;
for (const c of s) {
m[c] = (m[c] || 0) + 1;
if (m[c] > max) { max = m[c]; best = c; }
}
return best;
}from collections import Counter
def most_frequent(s):
return Counter(s).most_common(1)[0][0]Finding the mode is the essence of "top offender" reporting — the most common error code, the busiest endpoint.
Two characters tie for the highest count. Which does your code return, and is that acceptable?