Frequency Counter Pattern Using Hash Map in DSA C - Time & Space Complexity
We want to understand how fast the frequency counter pattern runs when counting items.
How does the time needed grow as the input list gets bigger?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
#include <string.h>
void frequencyCounter(char arr[], int freq[], int size) {
for (int i = 0; i < size; i++) {
freq[(unsigned char)arr[i]]++;
}
}
int main() {
char arr[] = "aabbcc";
int freq[256] = {0};
int size = strlen(arr);
frequencyCounter(arr, freq, size);
for (int i = 0; i < 256; i++) {
if (freq[i] > 0) {
printf("%c: %d\n", i, freq[i]);
}
}
return 0;
}
This code counts how many times each character appears in the input string using a frequency array as a hash map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over the input array to count frequencies.
- How many times: Exactly once for each character in the input (size times).
Each character is counted once, so the work grows directly with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 increments |
| 100 | About 100 increments |
| 1000 | About 1000 increments |
Pattern observation: The number of operations grows in a straight line as input size increases.
Time Complexity: O(n)
This means the time to count frequencies grows directly with the number of items in the input.
[X] Wrong: "Using a hash map makes counting slower because of extra lookups."
[OK] Correct: Hash maps or arrays let us find and update counts instantly, so counting is still fast and linear.
Knowing how frequency counting works and its time cost helps you solve many problems efficiently in interviews.
"What if we used a linked list instead of a hash map to count frequencies? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of a hash map
A hash map stores key-value pairs, allowing quick lookup and update of counts.Step 2: Apply to frequency counting
Using a hash map, we can track how many times each element appears by incrementing counts.Final Answer:
To count how many times each element appears in a collection -> Option DQuick Check:
Frequency counting = Counting elements [OK]
- Thinking hash map sorts elements
- Confusing frequency counting with removing duplicates
- Using arrays instead of hash maps for counting
Solution
Step 1: Recognize C language limitations
C does not have built-in hash map types like C++ STL's map or unordered_map.Step 2: Use array for frequency counting in C
We use an integer array of size 256 (for ASCII chars) initialized to zero to count frequencies.Final Answer:
int freq[256] = {0}; -> Option BQuick Check:
C uses arrays for frequency counting [OK]
- Using C++ STL syntax in C code
- Trying to declare map or unordered_map in C
- Not initializing frequency array to zero
char str[] = "aabbcc";
int freq[256] = {0};
for (int i = 0; str[i] != '\0'; i++) {
freq[(int)str[i]]++;
}
printf("%d", freq['b']);Solution
Step 1: Count occurrences of 'b' in the string
The string "aabbcc" has two 'b' characters at positions 2 and 3.Step 2: Check frequency array value for 'b'
freq['b'] is incremented twice, so freq['b'] = 2.Final Answer:
2 -> Option CQuick Check:
Count of 'b' = 2 [OK]
- Confusing character ASCII codes
- Forgetting null terminator in loop condition
- Printing freq for wrong character
char str[] = "hello";
int freq[256];
for (int i = 0; str[i] != '\0'; i++) {
freq[(int)str[i]]++;
}
printf("%d", freq['l']);Solution
Step 1: Check initialization of freq array
The freq array is declared but not initialized, so it contains garbage values.Step 2: Effect on frequency counting
Incrementing uninitialized values leads to incorrect counts; freq should be zeroed before use.Final Answer:
freq array is not initialized to zero -> Option AQuick Check:
Initialize freq array to zero before counting [OK]
- Assuming uninitialized arrays start at zero
- Using wrong printf format for integers
- Misunderstanding loop conditions with null terminator
s1 = "listen" and s2 = "silent", which approach using frequency counters correctly checks if they are anagrams in C?Solution
Step 1: Use frequency arrays for both strings
Create two arrays freq1 and freq2 of size 256, initialize to zero, count characters in s1 and s2 respectively.Step 2: Compare frequency arrays element-wise
If all counts match for every character, s1 and s2 are anagrams; otherwise, they are not.Final Answer:
Count frequencies of characters in both strings using arrays, then compare arrays element-wise -> Option AQuick Check:
Frequency arrays equal means anagrams [OK]
- Only counting one string's characters
- Comparing only string lengths or first characters
- Assuming sorting is the only way to check anagrams
Ready to prove it?
Pass the test and this pattern moves unknown
