Given a string, count how many times each character appears (e.g. "hello" -> h:1, e:1, l:2, o:1).
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.
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))Frequency maps power log analysis (which token appears most) and are the building block for the anagram and first-unique problems below.
The interviewer also wants the characters in first-seen order, but your HashMap scrambles them. What changes?