Loading

Quipoin Menu

Learn • Practice • Grow

data-structure-with-java / Frequency Counting
tutorial

Frequency Counting

Counting frequencies of elements is a classic problem easily solved with HashMap. It's used in many applications: word count, character frequency, finding duplicates, etc.

Example: Count frequency of each number in an array


public static Map countFrequencies(int[] arr) {
Map freq = new HashMap<>();
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
return freq;
}

Common frequency-based problems:
  • Find the element that appears more than n/2 times (Moore's voting).
  • Find the element with highest frequency.
  • Check if an array contains duplicates.
  • Group anagrams (count characters).

Character frequency in a string:


public static Map charFrequency(String s) {
Map freq = new HashMap<>();
for (char c : s.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
return freq;
}
Two Minute Drill
  • HashMap simplifies frequency counting.
  • getOrDefault() handles missing keys elegantly.
  • Common in problems: word count, duplicate detection, anagram check.
  • Frequency maps are the foundation for many algorithms.

Need more clarification?

Drop us an email at career@quipoinfotech.com