← Back to libraryQuestion 67 of 273
⌨️Java CodingIntermediate

Find the Most Frequent Character

📌 Definition:

Return the character that occurs most often in a string (e.g. "success" -> "s").

📖 Detailed Explanation:

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).

💻 Solutions:
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]
🔑 Key Points:
  • Count in one pass, then take the max entry
  • Decide tie-breaking rule up front
  • Ignore/normalize case if required
  • O(n) time, O(k) space
🌍 Real-World Example:

Finding the mode is the essence of "top offender" reporting — the most common error code, the busiest endpoint.

🎯 Scenario-Based Interview Question:

Two characters tie for the highest count. Which does your code return, and is that acceptable?