👶Explain Like I'm 5
Imagine you're counting how many candies of each color you have...
You make a tally chart on paper. Every time you see a red candy, you add a mark next to “Red”. Blue candy? Mark next to “Blue”. At the end, you can quickly see which color you have the most of!
Why is this smart? Instead of searching through all your candies every time someone asks “How many red ones?”, you just look at your chart. Super fast! O(1) lookup! 🚀
Real-world use cases:
- Count word frequency in a document
- Find duplicates in a list
- Group items by category
- Find first unique character
- Check if two strings are anagrams
Problem: Find Most Frequent Number
Array: [2,3,2,5,3,2,8,5]
Input Array
2
3
2
5
3
2
8
5
Hash Map (Tally Chart) 📊
Empty - Start counting to fill this up!
Processed
0/8
Unique Numbers
0
Map Size
0
Most Frequent
—
🎯 Click "Play" or "Next" to start counting!
💻Code Template
Copy this pattern!function findMostFrequent(arr) {
const hashMap = {}; // Our tally chart!
// Count frequencies
for (const num of arr) {
hashMap[num] = (hashMap[num] || 0) + 1;
}
// Find maximum
let maxNum = arr[0];
let maxCount = 0;
for (const [num, count] of Object.entries(hashMap)) {
if (count > maxCount) {
maxCount = count;
maxNum = Number(num);
}
}
return maxNum;
}
// Time: O(n) - Two passes through data
// Space: O(k) - k unique elements in hashMap
// Lookup: O(1) - Instant access by key!🎯When to Use Hash Map / Frequency Counting?
✅
Keywords: “count”, “frequency”, “occurrences”, “duplicates”
✅
Need to: Check if something exists quickly (O(1) lookup!)
✅
Track: Seen elements, pairs, or mapping between items
✅
Group: Items by some property (like anagrams)
💡
Pro Tip: Hash maps are like a phonebook - instant lookup instead of searching!