What if you could count everything in one quick pass without repeating work?
Why Frequency Counter Pattern Using Hash Map in DSA C?
Imagine you have a big box of colored marbles and you want to know how many marbles of each color you have. Counting each color one by one by sorting or scanning repeatedly takes a lot of time and effort.
Manually counting each color means checking every marble again and again. This is slow and easy to make mistakes, especially if the box is large or colors repeat many times.
The frequency counter pattern uses a hash map to keep track of counts as you look at each marble once. This way, you quickly know how many marbles of each color you have without repeating work.
int count = 0; for (int i = 0; i < n; i++) { count = 0; for (int j = 0; j < n; j++) { if (arr[j] == arr[i]) count++; } printf("%d appears %d times\n", arr[i], count); }
HashMap frequency; initHashMap(&frequency); for (int i = 0; i < n; i++) { int currentCount = get(&frequency, arr[i]); put(&frequency, arr[i], currentCount + 1); } printHashMap(&frequency);
This pattern lets you count and compare frequencies quickly, enabling fast checks for duplicates, anagrams, or matching data.
Checking if two words are anagrams by counting how many times each letter appears in both words and comparing the counts.
Manual counting is slow and error-prone for repeated data.
Frequency counter uses a hash map to count items in one pass.
It makes frequency-based problems easy and efficient.
