Frequency Patterns
The frequency pattern is one of the most common hash map tricks in coding interviews. The idea: spend \(O(n)\) time building a count map once, then answer any frequency-based query in \(O(1)\).
Think of it like a vote tally board at an election. Instead of re-counting ballots every time someone asks "how many votes did candidate X get?", you keep a running tally on the board. One pass through the ballots, then instant answers forever.
Anagram Detection
Two strings are anagrams if they have the same character frequencies. Sort both → \(O(n \log n)\) and awkward. Use frequency maps instead:
Duplicate Detection
"Has any element appeared more than once?" — add each element to a Set. First time you try to add something already in the Set, you've found a duplicate. \(O(n)\) time, \(O(n)\) space. Beats the \(O(n^2)\) nested loop approach.
← → arrow keys to step · click elements to interact
Frequency Count Pattern
Top-K Frequent Elements
Given an array, find the k most frequent elements. Naive approach: sort by frequency → \(O(n \log n)\). Better approach:
- Build frequency map: \(O(n)\)
- Use a min-heap of size k: iterate frequency map, push each (freq, element) into the heap. If heap grows beyond k, pop the minimum. Total: \(O(n \log k)\)
- Or use bucket sort: create buckets indexed by frequency (max frequency = n), scatter elements into buckets, then read top-k from the back. \(O(n)\) time!
Sliding Window with Frequency
Problems like "longest substring with at most k distinct characters" combine the sliding window technique with a frequency map. The map tracks how many of each character are in the current window. When distinct count exceeds k, shrink from the left, decrementing frequencies and removing entries that drop to zero.