Frequency Counter Pattern Using Hash Map in DSA Python - 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 list gets bigger?
Analyze the time complexity of the following code snippet.
def frequency_counter(arr):
freq = {}
for item in arr:
if item in freq:
freq[item] += 1
else:
freq[item] = 1
return freq
This code counts how many times each item appears in the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once for each item (n times if list size is n).
As the list gets bigger, the number of steps grows directly with the number of items.
| 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 list grows; doubling the list doubles the work.
Time Complexity: O(n)
This means the time to count frequencies grows in a straight line with the number of items.
[X] Wrong: "Checking if an item is in the frequency map takes time proportional to the list size."
[OK] Correct: Hash maps let us check and update counts in constant time, so each check is very fast regardless of list size.
Knowing how frequency counting works and its time cost helps you solve many problems efficiently and shows you understand key data structures.
"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 counting
The frequency counter pattern counts occurrences of each item in a list using a hash map (dictionary).Step 2: Compare options
Only Count how many times each item appears describes counting occurrences. Sorting, removing duplicates, or finding largest are different tasks.Final Answer:
Count how many times each item appears -> Option AQuick Check:
Frequency counter = count occurrences [OK]
- Confusing frequency counting with sorting
- Thinking it removes duplicates automatically
- Assuming it finds max/min values
Solution
Step 1: Identify data structure for frequency counter
A frequency counter uses a hash map, which in Python is a dictionary, created with curly braces {}.Step 2: Check options
freq = {} uses {}, which creates an empty dictionary. Others create list, tuple, or set, which are incorrect here.Final Answer:
freq = {} -> Option BQuick Check:
Empty dict = {} for frequency counter [OK]
- Using [] which creates a list, not a dictionary
- Using () which creates a tuple
- Using set() which creates a set, not a dict
def freq_counter(lst):
freq = {}
for item in lst:
freq[item] = freq.get(item, 0) + 1
return freq
print(freq_counter(['a', 'b', 'a', 'c', 'b', 'a']))Solution
Step 1: Count each item in the list
Loop goes through ['a', 'b', 'a', 'c', 'b', 'a']. 'a' appears 3 times, 'b' 2 times, 'c' 1 time.Step 2: Use freq.get(item, 0) + 1 to update counts
freq.get(item, 0) returns current count or 0 if not found, then adds 1.Final Answer:
{'a': 3, 'b': 2, 'c': 1} -> Option AQuick Check:
Count 'a'=3, 'b'=2, 'c'=1 [OK]
- Forgetting to add 1 to count
- Using freq[item] without get causing KeyError
- Miscounting occurrences
def freq_counter(lst):
freq = {}
for item in lst:
if item in freq:
freq[item] += 1
else:
freq[item] = 0
return freq
print(freq_counter(['x', 'y', 'x']))Solution
Step 1: Identify initialization error
When item is new, freq[item] is set to 0, but it should start at 1 because we found it once.Step 2: Fix initialization
Change freq[item] = 0 to freq[item] = 1 to count first occurrence correctly.Final Answer:
Change freq[item] = 0 to freq[item] = 1 -> Option DQuick Check:
First occurrence count must be 1 [OK]
- Setting initial count to 0 instead of 1
- Using list instead of dict for frequency
- Ignoring the else block
What will be the output of this code?
def same_frequency(lst1, lst2):
if len(lst1) != len(lst2):
return False
freq1 = {}
freq2 = {}
for num in lst1:
freq1[num] = freq1.get(num, 0) + 1
for num in lst2:
freq2[num] = freq2.get(num, 0) + 1
return freq1 == freq2
print(same_frequency([1,2,2,3], [2,1,3,2]))
print(same_frequency([1,2,2,3], [2,1,3,3]))Solution
Step 1: Build frequency dictionaries for both lists
freq1 counts {1:1, 2:2, 3:1}, freq2 for first call counts {2:2, 1:1, 3:1} which matches freq1.Step 2: Compare frequency dictionaries
For second call, freq2 counts {2:1, 1:1, 3:2} which differs from freq1, so returns False.Final Answer:
True False -> Option CQuick Check:
Same frequency = True, different frequency = False [OK]
- Only comparing lengths, not frequencies
- Not building frequency for both lists
- Returning True when frequencies differ
Ready to prove it?
Pass the test and this pattern moves unknown
