Pattern #06
Hashing
EssentialO(1) average lookup, frequency counting, grouping, and complement checks.
When to use
You need fast membership, counts, or grouping by a derived key. especially when a nested loop would be O(n²).
Recognition cues
- Two sum / complement to target
- Anagram / frequency equality
- Group by signature (sorted string, count tuple)
- First unique, duplicates, longest consecutive (set)
Common pitfalls
- Using list instead of set/map (O(n) lookup)
- Mutable keys or unstable signatures
- Hash collisions are rare; logic bugs in key design are common
90-second recognition drill
Which pattern fits best?
- Two sum / complement to target
- Anagram / frequency equality
- Group by signature (sorted string, count tuple)
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
Step 1 of 8
2
07
111
215
3map{ }
Statetarget=9seen={}
target = 9
How to think about it
Trade space for time. Store what you have seen under a key that makes the next check O(1) on average. The key is the whole problem: a complement, a set membership, a 26-letter count, or a frequency bucket.
Template shapes
| Shape | Key | Example |
|---|---|---|
| Complement | Look up target - value before storing the current index, so a value is not paired with itself |
LC 1 |
| Membership | Insert into a set. Already present means a duplicate. A consecutive run starts only when x - 1 is missing |
LC 217, LC 128 |
| Frequency | 26 letter counts, or sort both strings. Different lengths are false before counting | LC 242 |
| Group by signature | The key is the 26 counts or the sorted characters. An empty word is its own group | LC 49 |
| Frequency buckets | Count each value, then buckets indexed by that count. Read from the high end until k values. The highest count is at most n |
LC 347 |
Complexity baseline
Average O(n) time and O(n) space. Worst-case hash behavior is rarely the interview focus. The key design is.
From template to problem
- Name the key before the loop. A count tuple and a sorted string group the same anagrams (LC 49).
- For a complement, query the map before the insert (LC 1). Inserting first makes a value match itself.
- For a consecutive run, skip
xwhenx - 1is already in the set (LC 128). Duplicate copies ofxdo not extend the run. - Top-k by frequency on this path is buckets, not a heap. The bucket index is the count, and the count cannot exceed
n(LC 347).
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Hashing · Template
/** Hashing template: Two Sum with a value→index map. */
export function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i]!;
if (seen.has(need)) return [seen.get(need)!, i];
seen.set(nums[i]!, i);
}
throw new Error("No solution");
}
/** Hashing template: Two Sum with a value→index map. */
export function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i]!;
if (seen.has(need)) return [seen.get(need)!, i];
seen.set(nums[i]!, i);
}
throw new Error("No solution");
}
#StatusProblemTypeDifficultyDone
- 1#1 Two SumGuideeasy
- 2#49 Group AnagramsGuidemedium
- 3#128 Longest Consecutive SequenceGuidemedium
- 4#217 Contains DuplicateGuideeasy
- 5#242 Valid AnagramGuideeasy
- 6#347 Top K Frequent ElementsGuidemedium