ποΈ Hashing (Map / Set)
One-line summary: Use a hash table to achieve O(1) average-time lookup, insertion, and deletion β turning O(nΒ²) brute-force into O(n).
What is Hashing?β
Key Hash Table Componentsβ
- Hash Function: Converts keys into array indices
JavaScript Hash Structuresβ
- Map (
new Map()) β Key-value pairs; preserves insertion order; any type as key - Set (
new Set()) β Unique values only; no duplicates allowed - Object (
{}) β String/Symbol keys; prototype chain considerations - WeakMap/WeakSet β Garbage collection friendly; object keys only
Performance Characteristicsβ
- Average case: O(1) insert, lookup, delete
- Worst case: O(n) due to hash collisions (rare with good hash function)
- Space complexity: O(n) where n is number of elements
When to Use Hashing?β
β Perfect for:
- Fast lookups (checking if element exists)
- Counting frequencies (character/word counting)
- Removing duplicates (using Set)
- Caching/Memoization (storing computed results)
- Database indexing (quick record retrieval)
- Two-sum type problems (complement lookup)
β Not suitable for:
- Ordered data (use TreeMap/sorted structures)
- Range queries (use segment trees/arrays)
- Memory-constrained environments (overhead of hash table)
- Small datasets (array iteration might be faster)
π Visual Learningβ
Hash Table Structureβ
Understanding how hash functions map keys to array indices and handle collisions
Step-by-step visualization of key hashing, collision detection, and resolution strategies
Comparing array-based storage vs hash table organization for efficient data access
Time & Space Complexityβ
| Operation | Average | Worst |
|---|---|---|
| Insert | O(1) | O(n) |
| Lookup | O(1) | O(n) |
| Delete | O(1) | O(n) |
| Space | O(n) | O(n) |
Common Patternsβ
Pattern 1 β Frequency Countβ
const freq = new Map();
for (const ch of s) freq.set(ch, (freq.get(ch) || 0) + 1);
Pattern 2 β Complement Lookup (Two Sum)β
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const comp = target - nums[i];
if (seen.has(comp)) return [seen.get(comp), i];
seen.set(nums[i], i);
}
Pattern 3 β Canonical Key (Group Anagrams)β
const groups = new Map();
for (const w of words) {
const key = w.split('').sort().join('');
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(w);
}
Pattern 4 β Set Membership (Contains Duplicate)β
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) return true;
seen.add(n);
}
return false;
Pitfallsβ
- Using object
{}as map β breaks with keys like"__proto__"β prefernew Map() - Comparing object keys by reference, not value
- Forgetting that
Map.sizeβObject.keys(obj).length
Practice Problemsβ
| Problem | Difficulty | Solution |
|---|
| LC 1 β Two Sum | Easy | View Solution | | LC 217 β Contains Duplicate | Easy | View Solution | | LC 242 β Valid Anagram | Easy | View Solution | | LC 929 β Unique Email Addresses | Easy | View Solution | | LC 575 β Distribute Candies | Easy | View Solution | | LC 349 β Intersection of Two Arrays | Easy | View Solution | | LC 219 β Contains Duplicate II | Easy | View Solution | | LC 383 β Ransom Note | Easy | | | LC 387 β First Unique Character in a String | Easy | | | LC 389 β Find the Difference | Easy | | | LC 448 β Find All Numbers Disappeared in an Array | Easy | | | LC 771 β Jewels and Stones | Easy | | | LC 1002 β Find Common Characters | Easy | | | LC 1207 β Unique Number of Occurrences | Easy | | | CC β Frequency of Characters (FREQ) | Easy | | | CC β Count Distinct Elements (DISTELEM) | Easy | | | LC 49 β Group Anagrams | Medium | View Solution | | LC 347 β Top K Frequent Elements | Medium | View Solution | | LC 128 β Longest Consecutive Sequence | Medium | View Solution | | LC 167 β Two Sum II | Medium | View Solution | | LC 3 β Longest Substring Without Repeating Characters | Medium | | | LC 36 β Valid Sudoku | Medium | | | LC 187 β Repeated DNA Sequences | Medium | | | LC 454 β 4Sum II | Medium | | | LC 560 β Subarray Sum Equals K | Medium | | | LC 692 β Top K Frequent Words | Medium | | | LC 974 β Subarray Sums Divisible by K | Medium | | | LC 1010 β Pairs of Songs With Total Durations Divisible by 60 | Medium | | | CC β Subarray with Given Sum (SUBSUM) | Medium | | | CC β Hash Table Operations (HASHTBL) | Medium | | | LC 30 β Substring with Concatenation of All Words | Hard | | | LC 41 β First Missing Positive | Hard | | | LC 149 β Max Points on a Line | Hard | | | LC 269 β Alien Dictionary | Hard | | | LC 336 β Palindrome Pairs | Hard | | | CC β Advanced Hashing (ADVHASH) | Hard | |
Related Topicsβ
- Prefix Sum β hash maps power "subarray sum = K"
- Sliding Window β freq maps track window contents
- Two Pointers