Overview
Hash map (dict) se elements count karo — O(1) lookup aur insert se O(n) total counting possible.
Analogy
Jaise attendance register — student ka naam key, count value.
Step-by-step
- Empty dict {} se start karo
- Loop mein: d[key] = d.get(key, 0) + 1
- Ya collections.Counter use karo directly
- dict.items() se frequency pairs iterate karo
Visual
words = ["apple","banana","apple","cherry","banana","apple"]
from collections import Counter
Counter(words) # {"apple": 3, "banana": 2, "cherry": 1}
Common mistakes
- KeyError — d[key] += 1 seedha error deta hai agar key nahi ho
- defaultdict(int) ya .get(key, 0) use karo
- Counter negative counts support karta hai — unexpected ho sakta hai
Practice questions
- Most frequent element find karo
- Two arrays ka intersection find karo counting se