Frequency Counter Pattern Using Hash Map in DSA C# - Time & Space Complexity
We want to understand how fast we can count how many times each item appears in a list using a hash map.
The question is: how does the time needed grow as the list gets bigger?
Analyze the time complexity of the following code snippet.
var frequency = new Dictionary<char, int>();
string input = "example";
foreach (char c in input)
{
if (frequency.ContainsKey(c))
frequency[c]++;
else
frequency[c] = 1;
}
This code counts how many times each character appears in the string.
- Primary operation: Looping through each character in the string once.
- How many times: Exactly once for each character (n times, where n is string length).
- Inside loop: Checking and updating the hash map, which is very fast (constant time).
As the string gets longer, the number of steps grows directly with the number of characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and updates |
| 100 | About 100 checks and updates |
| 1000 | About 1000 checks and updates |
Pattern observation: The work grows evenly as the input grows; doubling input doubles work.
Time Complexity: O(n)
This means the time to count frequencies grows in a straight line with the input size.
[X] Wrong: "Since we check inside a loop, it must be O(n²) because of nested work."
[OK] Correct: The hash map lookup and update happen in constant time, not a loop inside a loop, so it stays O(n).
Knowing how to count items quickly using a hash map is a key skill. It shows you can use simple tools to solve common problems efficiently.
"What if we used a list instead of a hash map to count frequencies? How would the time complexity change?"
Practice
Solution
Step 1: Understand frequency counter pattern
The frequency counter pattern uses a hash map to store counts of each element in a collection.Step 2: Identify the purpose
This pattern helps to quickly find how many times each element appears, which is useful for comparisons or validations.Final Answer:
To count how many times each element appears in a collection -> Option AQuick Check:
Frequency counter = count elements [OK]
- Confusing frequency counting with sorting
- Thinking it reverses elements
- Assuming it finds max value
Solution
Step 1: Identify correct data structure for frequency counting
A Dictionary maps each integer to its count, perfect for frequency counting.Step 2: Check other options
List<int> stores values but not counts, HashSet<int> stores unique values without counts, int[] is fixed size and less flexible.Final Answer:
var freq = new Dictionary(); -> Option CQuick Check:
Dictionary for frequency map [OK]
- Using List instead of Dictionary for counts
- Using HashSet which stores only unique elements
- Using fixed-size array without mapping keys
var arr = new int[] {1, 2, 2, 3, 3, 3};
var freq = new Dictionary();
foreach (var num in arr) {
if (freq.ContainsKey(num)) freq[num]++;
else freq[num] = 1;
}
foreach (var kvp in freq) {
Console.Write(kvp.Key + ":" + kvp.Value + " ");
}Solution
Step 1: Count frequencies in array
1 appears once, 2 appears twice, 3 appears three times.Step 2: Output order in Dictionary foreach
Dictionary preserves insertion order in recent C# versions, so output is 1:1 2:2 3:3.Final Answer:
1:1 2:2 3:3 -> Option BQuick Check:
Count each element correctly [OK]
- Mixing counts of elements
- Assuming Dictionary outputs sorted keys
- Forgetting to increment counts
string text = "hello";
var freq = new Dictionary();
foreach (char c in text) {
freq[c] += 1;
}
Solution
Step 1: Analyze dictionary usage
freq[c] += 1 assumes key c exists, but keys are not added before incrementing.Step 2: Identify exception cause
Accessing freq[c] when c is not a key throws KeyNotFoundException.Final Answer:
Trying to increment a key that may not exist causes a KeyNotFoundException -> Option AQuick Check:
Increment without key check causes error [OK]
- Assuming keys auto-initialize in Dictionary
- Ignoring exception on missing keys
- Misunderstanding foreach syntax
arr1 and arr2, which C# code snippet correctly uses the frequency counter pattern to check if arr2 contains the squares of all elements in arr1 with matching frequencies?Solution
Step 1: Build frequency maps for arr1 and arr2
freq1 counts elements in arr1, freq2 counts elements in arr2.Step 2: Check if freq2 has squares of freq1 keys with matching counts
For each key in freq1, check if freq2 contains key squared with same frequency.Final Answer:
Code snippet C correctly implements the frequency counter pattern for this problem -> Option DQuick Check:
Compare freq1 keys squared with freq2 frequencies [OK]
- Comparing frequency dictionaries without squaring keys
- Decrementing counts without checking all keys
- Using SequenceEqual without sorting or matching keys
Ready to prove it?
Pass the test and this pattern moves unknown
