Counting frequencies: anagrams, duplicates and the most common item
Count how many times each value appears, in one pass. The pattern behind anagrams, "first unique character", "top K frequent" and many sliding window problems.
In short
Walk the input once and keep a count per value in a hash map (or an array of 26 for letters). Comparing or querying counts replaces sorting and nested loops: O(n) time, O(k) space for k distinct values.
The idea: tally marks
Two words are anagrams if they use the same letters the same number of times. Sorting both works (O(n log n)), but counting is simpler: add one for each letter of the first word, subtract one for each letter of the second. If everything ends at zero, they match.
t
count (char → times)
1def is_anagram(s, t):2 if len(s) != len(t):3 return False4 count = {}5 for ch in s:6 count[ch] = count.get(ch, 0) + 17 for ch in t:8 count[ch] = count.get(ch, 0) - 19 if count[ch] < 0:10 return False11 return True
Variables
Array of 26 or hash map?
Array of 26 (or 128)
- Only lowercase letters (or ASCII)
- Fastest in practice, O(1) extra space
count[ord(c) - ord('a')] += 1
Hash map
- Any keys: Unicode, numbers, words
- O(k) space for k distinct keys
Counter(s)in Python,Mapin TS,HashMapin Java
Problems that are secretly counting
| Problem | What you count |
|---|---|
| Valid anagram | Letters of s minus letters of t: all zero? |
| First unique character | Count all, then the first with count 1 |
| Group anagrams | Use the count (or sorted word) as the map key |
| Top K frequent elements | Count, then a heap or bucket sort by count |
| Ransom note | Letters available in the magazine vs needed |
Key takeaways
- 01Count each value once in O(n); compare or query counts instead of sorting.
- 02Lowercase letters: an array of 26. Anything else: a hash map.
- 03Anagrams, first unique, group anagrams and top K are all counting.
- 04Counts inside a window are the engine of many sliding window problems.
Check your understanding
1 of 3
How do you check if two strings are anagrams in O(n)?
Related topics
Hash maps
A hash map stores key → value pairs and finds any key in O(1) on average. Whenever a loop keeps asking "have I seen this before?", a hash map usually turns O(n²) into O(n).
8 min read →Sliding window
For questions about a contiguous subarray or substring, keep a window: grow it on the right, and shrink it from the left only when it breaks the rule. Each element enters and leaves once: O(n) instead of checking all O(n²) ranges.
9 min read →