Hash Map
O(n)Use a hash map for O(1) lookup to track seen elements, frequencies, or complement values during array traversal.
When to Use
- Finding pairs/triplets with target sum
- Counting frequency of elements
- Checking for duplicates or anagrams
- Storing indices for later lookup
Pattern Variants
Complement Lookup
Store complement values (target - current) to find pairs in single pass.
Use for: Two Sum, pair with target sum
Frequency Counter
Count occurrences of each element for comparison or finding duplicates.
Use for: Valid Anagram, first unique character, majority element
Index Storage
Store indices of elements for later reference or constraint checking.
Use for: Contains Duplicate II, finding subarrays with constraints
Interactive Visualization
1function twoSum(nums, target) {2 const map = new Map()34 for (let i = 0; i < nums.length; i++) {5 const complement = target - nums[i]67 if (map.has(complement)) {8 return [map.get(complement), i]9 }1011 map.set(nums[i], i)12 }13 return []14}
Practice this Pattern
Two Sum
Find two numbers that add up to target using hash map
Valid Anagram
Check if two strings are anagrams using character frequency
Group Anagrams
Group strings that are anagrams of each other
Implement Trie (Prefix Tree)
Build insert/search/startsWith on a trie of characters
Design Add and Search Words Data Structure
Support addWord and search with wildcard dot matching
Replace Words
Replace words in a sentence by the shortest dictionary root
Search Suggestions System
Return up to 3 lexicographically sorted suggestions while typing each prefix
Stream of Characters
Implement a stream checker that detects any suffix matching inserted words
Word Search II
Find all words in a board using trie-guided DFS
Short Encoding of Words
Minimize encoded length by merging shared suffixes in a trie
Magic Dictionary
Implement buildDict + search allowing one character mismatch
Longest Word in Dictionary
Find the longest word that can be built one character at a time
Top K Frequent Elements
Find the k most frequent elements using bucket sort