Counting things with a hash map
, majority element, most frequent: they're all “count each value”. A from value to count does it in one pass.
The idea
A hash map (dict in Python) stores key → value pairs with lookups. Use the item as the key and how many times you've seen it as the value.
Two strings are anagrams exactly when every letter has the same count in both, so counting turns the problem into comparing two maps.
Worked example
Valid Anagram: “listen” vs “silent”
- Count “listen”: l:1 i:1 s:1 t:1 e:1 n:1
- Count “silent”: s:1 i:1 l:1 e:1 n:1 t:1
- Same keys with the same counts → anagram.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
items = "banana"
seen
{ } empty — nothing seen yetSolution · Pythonline 8
from collections import Counter def is_anagram(s, t):return Counter(s) == Counter(t) # Without Counter:def counts(s):seen = {}for ch in s:seen[ch] = seen.get(ch, 0) + 1return seenStep 1 of 8· line 8
An empty map: letter → how many times we've seen it.
time, O(k) space for k distinct items.
How to spot it
- “anagram”, “frequency”, “most common”, “appears more than n/2 times”.
Common mistakes
- Forgetting the length check shortcut: different lengths can't be anagrams.
- Sorting both strings works but is ; counting is O(n).
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
- Second-largest distinct elementIndexing and walking through an arrayPractise ✎
- Count how often each number appearsCounting with a hash mapPractise ✎
- Remove duplicate characters, keep the firstA set for “have I seen this?”Practise ✎
- Reverse the order of wordsBuilding a new string or array as the answerPractise ✎
Practise it
Go further
Up next for you · Beginner
“Have I seen this?” is a set →