iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Hash Maps

A hash map gives you O(1) average-case insert, lookup, and delete. Under the hood: an array of buckets, a hash function, and a strategy for collisions. They’re the single most useful data structure in interviews.

Patterns that use a hash map

EXAMPLE
// 1) Counting frequencies
function mostCommon(words) {
    const counts = new Map();
    for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
    return [...counts].sort((a, b) => b[1] - a[1])[0][0];
}

// 2) Two-sum — O(n) instead of O(n²)
function twoSum(nums, target) {
    const seen = new Map();
    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);
    }
}

// 3) Memoisation cache
const cache = new Map();
function fib(n) {
    if (n < 2) return n;
    if (cache.has(n)) return cache.get(n);
    const v = fib(n - 1) + fib(n - 2);
    cache.set(n, v);
    return v;
}

// 4) Group anagrams
const groups = new Map();
for (const s of strs) {
    const key = [...s].sort().join('');
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(s);
}

Why it matters

JS Map beats plain {} for hot-path keys: O(1) regardless of size, preserves insertion order, supports any key type. Set is the same idea for membership.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
const counts = new Map();
for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
const max = [...counts.entries()].reduce((a, b) => a[1] > b[1] ? a : b);
Try it Yourself »

Exercise

JS class for hash-map style lookups.

const counts = new ();

Test yourself

Q1. Hash map performance degrades to O(n) when…
Q2. JS Maps preserve…
Q3. For counting word frequency, use…

Discussion

Loading…