← Back to libraryQuestion 56 of 273
⌨️Java CodingIntermediate

Count the Occurrences of Each Character

📌 Definition:

Given a string, count how many times each character appears (e.g. "hello" -> h:1, e:1, l:2, o:1).

📖 Detailed Explanation:

Scan once, accumulating counts in a hash map keyed by character. A single pass is O(n). For fixed ASCII input an int[256] frequency array avoids hashing overhead. Use an ordered map if first-seen order must be preserved.

💻 Solutions:
public static Map<Character,Integer> countChars(String s) {
    Map<Character,Integer> m = new LinkedHashMap<>();
    for (char c : s.toCharArray()) m.merge(c, 1, Integer::sum);
    return m;
}
function countChars(s) {
  const m = {};
  for (const c of s) m[c] = (m[c] || 0) + 1;
  return m;
}
from collections import Counter

def count_chars(s):
    return dict(Counter(s))
🔑 Key Points:
  • Single pass with a hash map — O(n)
  • int[256]/int[128] array for ASCII
  • Ordered map preserves first-seen order
  • Foundation for anagram / unique-char problems
🌍 Real-World Example:

Frequency maps power log analysis (which token appears most) and are the building block for the anagram and first-unique problems below.

🎯 Scenario-Based Interview Question:

The interviewer also wants the characters in first-seen order, but your HashMap scrambles them. What changes?