Skip to main content

πŸ—‚οΈ 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​

Hash Table Visualization Understanding how hash functions map keys to array indices and handle collisions

Hash Function Flow Step-by-step visualization of key hashing, collision detection, and resolution strategies

Array vs Hash Table Comparing array-based storage vs hash table organization for efficient data access


Time & Space Complexity​

OperationAverageWorst
InsertO(1)O(n)
LookupO(1)O(n)
DeleteO(1)O(n)
SpaceO(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__" β€” prefer new Map()
  • Comparing object keys by reference, not value
  • Forgetting that Map.size β‰  Object.keys(obj).length

Practice Problems​

ProblemDifficultySolution

| 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 | |