Technique
Bucket / Counting Sort
Distribute items into buckets by a bounded key (frequency, value range) so ordering is O(n + range) instead of O(n log n).
Learn firstHash Map / Hash Set Lookup
0%
mastery
0/5 solved
0/5 solved
Recognise it
The signal
keys bounded by n (frequencies)
1Brute force
Comparison sort O(n log n).
2The observation
Comparison sorting: bounded integer keys can be indexed directly.
3Why it works
Bucket b holds exactly the items with key b (or in range b).
Reach for it when
- +top-k frequent in O(n)
- +maximum gap between sorted elements in O(n)
Not when
- ×unbounded keys
- ×need stable order of complex comparators
Practice
0/5 solved
- H-IndexGoogle, AdobeMedium
- Custom Sort StringMetaMedium
- Top K Frequent ElementsAmazon, MetaMedium
- Sort Characters By FrequencyAmazon, UberMedium
- Sliding Window ModeCSESMedium
Pitfalls
Misconceptions
- !thinking heaps are required for top-k frequent