Bird
0
0
DSA Cprogramming~3 mins

Why Frequency Counter Pattern Using Hash Map in DSA C?

Choose your learning style9 modes available
The Big Idea

What if you could count everything in one quick pass without repeating work?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
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);
}
After
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);
What It Enables

This pattern lets you count and compare frequencies quickly, enabling fast checks for duplicates, anagrams, or matching data.

Real Life Example

Checking if two words are anagrams by counting how many times each letter appears in both words and comparing the counts.

Key Takeaways

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.