Frequency Counting with HashMap Java | Fresher Interview
Fast recall
Quick revision
Core answer
HashMap (or int[] for bounded keys) to count occurrences in one O(n) pass. The idiom is map.merge(key, 1, Integer::sum) or getOrDefault(key, 0) + 1. With counts in hand you answer 'most frequent', 'first unique', 'duplicates', and 'anagram' questions in O(n) instead of O(n^2).Whether you can build a frequency map in one pass and use the clean merge/getOrDefault idiom
Re-scanning the array per element (O(n^2)) instead of counting once, or NPE on a missing key
Use map.merge for concise counting and pick int[] when keys are small bounded integers/letters
Interview-ready guide
Interview answer
Frequency counting is one of the patterns I reach for constantly.
The idea is to build a map from each element to the number of times it appears, in a single linear pass over the input. For arbitrary keys I use a HashMap from the element to an integer count. For bounded keys, like lowercase letters or small integers, I use a plain integer array instead, because it's faster and uses constant space.
In Java the clean way to do the counting is map dot merge, passing the key, one, and Integer sum, which either inserts a count of one or adds one to the existing count. The alternative idiom is getOrDefault of the key with a default of zero, plus one.
Both of these matter because the naive version, map dot get of the key plus one, throws a null pointer exception on the very first occurrence when the key isn't there yet. Once I have the counts, the actual interview question is usually answered with a second pass. If I want the most frequent element, I scan the entries for the largest count.
If I want the first non-repeating character, I walk the original string and return the first one whose count is one. Anagram checks, duplicate detection, top-K frequent, they all build on this same counting step. The big win is complexity: counting once and then querying is O of n, whereas the brute-force approach of counting each element by re-scanning the whole array is O of n squared.
So whenever a problem mentions how many times, most, or unique, frequency counting is the first thing I consider.
Frequency Counting with HashMap Java | Fresher Interview
Direct Answer
The frequency counting pattern uses a HashMap<Element, Integer> (or int[] for bounded keys) to count occurrences in one O(n) pass. The idiom is map.merge(key, 1, Integer::sum) or getOrDefault(key, 0) + 1. With counts in hand you answer 'most frequent', 'first unique', 'duplicates', and 'anagram' questions in O(n) instead of O(n^2).
Deep Dive & Architecture
A frequency map stores one entry per distinct value: the key is the value and the map value is the number of times it has appeared. For each item, read its old count, add one, and store the result.
Worked example: banana
The counts change as b=1, a=1, n=1, a=2, n=2, and a=3. The final map is {b=1, a=3, n=2}. In Java, the update can be written as counts.put(ch, counts.getOrDefault(ch, 0) + 1) or counts.merge(ch, 1, Integer::sum).
Once built, the same map can answer several questions without rescanning: which value is most frequent, whether two inputs have equal counts, which values are duplicates, or whether a character occurs exactly once.
The scan is O(n) average time and the map uses O(k) space for k distinct values. A fixed counter array is simpler and faster when the key range is small and known, such as lowercase letters or scores from 0 to 100. A HashMap is the safer general choice when keys are sparse, negative, strings, or objects.
Do not rely on a HashMap's iteration order when the answer depends on the original sequence; make a second pass over the input or use an ordered structure deliberately.
Code Example
Map<Character, Integer> freq = new HashMap<>();
String s = "banana";
for (char c : s.toCharArray())
freq.merge(c, 1, Integer::sum); // count in one pass
// freq = {b=1, a=3, n=2}
// Query: most frequent character
char best = ' '; int max = 0;
for (var e : freq.entrySet())
if (e.getValue() > max) { max = e.getValue(); best = e.getKey(); }
// best = 'a' (count 3)
// For lowercase letters, an int[26] is faster:
int[] count = new int[26];
for (char c : s.toCharArray()) count[c - 'a']++;
Common Mistakes & Pitfalls
- Re-scanning per element: counting occurrences with a nested loop is O(n^2); one pass with a map is O(n).
- NPE on first occurrence:
map.get(key) + 1throws on a missing key - usegetOrDefaultormerge. - HashMap when int[] fits: for
a-zor small ints,int[]is faster and O(1) space. - Modifying map while iterating: collect results separately or use an iterator's
remove.
Check your understanding
Answer these without looking back at the article.
- What happens when two keys produce the same hash code? How does a HashMap handle it?
- How would you use a HashMap to find the first non-repeating character in a string?
- How does a HashMap work internally in Java?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.