You just crushed Contains Duplicate — nice! 🎉 Now let's level up the dictionary (hash map) skill that powers a TON of array problems.
Picture this: it's election day at school. Votes are coming in one by one — "Alice", "Bob", "Alice", "Bob", "Charlie", "Bob". How do you count who's winning? You grab a piece of paper and make tally marks next to each name. That paper? That's a dictionary. 🗳️
The Frequency Counter Pattern:
Here's the pattern visualized:
The slick Python trick is dict.get(key, 0) — it returns the current count if the key exists, or 0 if it doesn't. Then just add 1. No messy if/else needed!
⏱ Time Complexity: O(n) — One pass through the array. Each dictionary lookup/insert is O(1) on average.
💾 Space Complexity: O(n) — In the worst case, every element is unique, so the dictionary has n entries.
Why does this matter? Because the Two Sum problem coming up next uses a dictionary for lookups — but the pattern of "build a dict in one pass" starts right here. Master counting first, then lookups become second nature. 🧠
def count_frequency(arr):
freq = {}
for item in arr:
freq[item] = freq.get(item, 0) + 1
return freq
print(count_frequency([1, 2, 1, 3, 1, 2]))
print(count_frequency(['a', 'b', 'a', 'b', 'c', 'b']))
freq = count_frequency(['a', 'b', 'a', 'b', 'c', 'b'])
most = max(freq, key=freq.get)
print(f"Most frequent: {most} ({freq[most]} times)")