Hash Tables

A structure that finds a value almost instantly by its key, without searching everything.

What is it?

Searching an array means checking items one at a time, which gets slow with lots of data. A hash table turns a key (like a name or an id) into a number with a hash function, then uses that number to jump straight to where the value is stored.

In JavaScript, plain objects and the Map class both build on this idea.

Explain like I'm 10

A hash table is like a theater coat check. Instead of searching every coat, you get a numbered ticket (the hash), and the attendant goes straight to that spot for your coat.

Examples

Using an object (or Map) as a hash table

const ages = {};

ages["amara"] = 28;
ages["diego"] = 34;

console.log(ages["amara"]); // 28 — near-instant lookup, not a search

const map = new Map();
map.set("amara", 28);
console.log(map.get("amara")); // 28

How it works

A hash function turns a key into a number (a "hash") that maps to a storage slot. A lookup hashes the key, jumps to that slot and reads the value, with no scanning.

Sometimes two keys hash to the same slot (a "collision"). The table handles this, for example by storing a small list at that slot.

key "amara"
       ↓ hash function
    number: 42
       ↓
   slot 42 → 28

Why does it exist?

Hash tables give O(1) average lookups, insertions and deletions. That makes them essential for counting frequencies, caching results, removing duplicates, and building sets and dictionaries.

When to use it

Use a hash table (object or Map) when you need fast lookup by key: counting occurrences, checking for duplicates, caching results, or any kind of dictionary.

When not to use it

If you need items in a specific sequence, a hash table doesn't guarantee position the way an array does. For a small, fixed handful of values, checking each one directly can be faster.

Common mistakes

  • Relying blindly on object key order. Modern JavaScript mostly preserves it for string keys, but know the rules rather than assume.

  • Using an object when a Map would be safer, e.g. when keys aren't simple strings or when key order and size (.size) matter.

  • Forgetting that average O(1) lookup can degrade if many keys collide (rare, but real).

Practice exercises

  1. Easy:

    Use an object to count how many times each word appears in a sentence.

  2. Medium:

    Write a function that returns true if an array has any duplicate values, using a hash table for O(n) performance.

  3. Hard:

    Solve the 'two sum' problem (find two numbers in an array that add up to a target) in O(n) time using a hash table.

Interview questions

What is a hash function?

A function that turns a key into a number that decides where its value is stored, ideally spreading keys evenly across slots.

What is the average time complexity of a hash table lookup?

O(1) on average, since the hash usually leads straight to the right slot.

What is a hash collision, and how is it handled?

Two different keys hash to the same slot. A common fix is to store several entries at that slot (e.g. in a small list) and check each one.

What three properties should a good hash function have?

Deterministic (the same key always gives the same hash), fast (so it doesn't cancel the O(1) benefit), and uniform (keys spread evenly across slots, keeping collisions, chains and probe sequences short).

What is the load factor of a hash table, and why does it matter?

Stored entries divided by slots (n / capacity). As it rises, more keys share slots, so collisions grow and chains (or probe sequences) get longer, pushing lookups from O(1) toward O(n) in the worst case. Implementations resize when it crosses a threshold.

Why is resizing a hash table (rehashing) an O(n) operation, and why doesn't that ruin the 'O(1) average' claim for insertion?

Each entry's slot depends on hash(key) % capacity, so a new capacity moves almost every key. Resizing reinserts every entry into a bigger array: O(n). But resizes (usually doubling) get rarer as the table grows, so, like a dynamic array, the cost amortizes to O(1) per insertion.

What is separate chaining, and what does it cost in the worst case if every key hashes to the same slot?

Each slot holds a small structure (usually a linked list, sometimes a balanced tree) of the entries that hashed there. A lookup hashes to the slot, then scans that structure. If every key landed in one slot, it would hold all n entries and lookup becomes O(n), like a linear scan.

What is open addressing, and how does linear probing resolve a collision under it?

Open addressing stores every entry directly in the array, with no secondary structure. On a collision, linear probing checks the next slot ((hash + 1) % capacity), then the next, until it finds an empty one. Insert and lookup follow the same probe sequence.

What is primary clustering in linear probing, and why does it make things worse as load factor rises?

Colliding keys fill one unbroken run of occupied slots. Any new key hashing into that run probes through the whole cluster, and each insertion makes it longer. Clusters grow and merge, hurting average probe length well before the load factor nears 1.

How does quadratic probing try to reduce clustering compared to linear probing, and what's the tradeoff?

It checks slots at growing squared offsets (hash+1², hash+4, hash+9...), spreading probes out so collisions don't pile into one run. The tradeoff is secondary clustering: keys with the same starting slot still follow the same probe sequence.

How does double hashing address both primary and secondary clustering?

The probe step comes from a second hash of the key, so keys colliding at the same slot almost always take different steps and sequences. Linear probing uses one fixed step for everyone; quadratic probing uses the same offsets for every key colliding at a slot.

Why can't you just delete an entry from an open-addressing hash table by clearing its slot to empty?

A lookup probes until it hits an empty slot, then concludes the key is absent. If a slot in the middle of a probe sequence is cleared, a lookup for a key stored further along stops there early and wrongly reports it missing.

How do open-addressing hash tables actually support deletion, given the problem with clearing a slot outright?

They mark the slot with a 'tombstone' instead of clearing it. Lookups treat a tombstone as 'occupied, keep probing', while inserts can reuse it. Probing stays correct and the slot can still be reclaimed.

Why does average-case hash table lookup stay close to O(1) even though the worst case is O(n)?

With a good hash function and a bounded load factor (kept by resizing), the expected number of entries per slot stays a small constant, whatever n is. O(n) only happens when most or all keys collide into one slot.

What is a 'hash flooding' attack, and how do some languages defend against it?

An attacker who knows or guesses the hash function sends many keys that deliberately collide, pushing each operation toward O(n) and causing a denial of service. Some languages/runtimes defend by seeding the hash function with a random value at startup, so collisions can't be predicted without the secret seed.

What is the practical difference between using a plain JavaScript object and a `Map` as a hash table?

Map accepts any value as a key (including objects and functions, compared by reference), reliably keeps insertion order, and reports .size. A plain object coerces non-symbol keys to strings, inherits prototype properties unless guarded, and orders integer-like keys numerically before all others.

Two different object instances with identical contents are used as keys in a JavaScript `Map` — are they treated as the same key?

No. Map compares object keys by reference (the same object in memory), not by contents. Two separate objects that both look like { a: 1 } are two keys.

Why is `NaN` a usable `Map` key, given that `NaN !== NaN` in JavaScript?

Map compares keys with SameValueZero, not ===. SameValueZero treats NaN as equal to itself (its one difference from ===), so map.set(NaN, 1) then map.get(NaN) returns 1.

What's the time complexity of checking whether an array contains any duplicate values, using a hash table versus not?

With a hash table (a Set): O(n), one pass with an O(1) average check per element. Without one: comparing every pair is O(n²); sorting then scanning adjacent items is O(n log n), better but still slower than the hash table.

How does the 'two sum' problem go from O(n²) to O(n) using a hash table?

Brute force checks every pair: O(n²). Instead, walk the array once and check whether target - number is already in a hash map (value to index); if so, you've found the pair. Each lookup and insert is O(1) average, so the pass is O(n).

Why can't you efficiently binary-search or iterate a hash table in sorted key order the way you can an array?

A key's slot depends on its hash, not on other keys' order, so similar keys land in unrelated slots. With no order to exploit, finding a range or the min/max key means scanning every entry, O(n), even though looking up a known key is O(1) average.

What is a hash set, and how does it relate to a hash table?

A hash table that stores only keys, no values. It uses the same hashing and collision handling to answer 'have I seen this before?' in O(1) average time, for membership tests and removing duplicates.

Why do a hash map and a doubly linked list, used together, give an LRU cache O(1) `get` and `put`?

The hash map finds a key's list node in O(1) average. The doubly linked list keeps entries in recency order, and since each node knows both neighbors, it removes from anywhere and re-inserts at the front in O(1). Together the cache can find, reorder and evict without scanning.

What is consistent hashing, and what problem does it solve that a plain `hash(key) % N` scheme doesn't?

With hash(key) % N, adding or removing one server (changing N) moves almost every key, invalidating nearly the whole distributed cache. Consistent hashing puts keys and servers on a shared ring of hash values and assigns each key to the next server clockwise. Adding or removing a server only moves the keys between it and its neighbor.

What is a Bloom filter, and how is it different from a hash set?

A Bloom filter is a probabilistic structure using a fixed-size bit array and several hash functions. It answers 'definitely not present' or 'possibly present', accepting a small false-positive rate in exchange for big space savings, since it never stores the keys. A hash set stores the real keys and is always exact, but its memory grows with the number of keys.

Why might a hash table implementation upgrade a slot's collision list into a balanced tree once it grows past a certain size (as Java's `HashMap` does)?

A linked-list bucket degrades to O(n) lookup if many keys collide there (from hash flooding or bad luck). Turning a long bucket into a balanced tree (like a red-black tree) caps worst-case lookup in that bucket at O(log n), for a little extra bookkeeping.

What is perfect hashing, and why does it only apply to a fixed, known set of keys?

It builds a hash function (often two-level) with zero collisions for a specific, known set of keys, giving true O(1) worst-case lookup. Building it needs the full key set in advance, so it can't handle arbitrary future insertions.

What is cuckoo hashing, and what's its worst-case lookup guarantee?

Each key has two candidate slots (from two hash functions, often across two tables), and lookup checks only those two: O(1) worst case, unlike chaining's O(n). Insertion costs more: if both slots are taken, it evicts an occupant and re-inserts that key into its alternate slot. That can cascade into a chain of evictions or, rarely, a full rehash if a cycle is detected.

What's the time complexity of iterating over every entry in a hash table, and does table capacity affect it?

In general O(n + capacity): visit every entry (O(n)) and check every slot (O(capacity)) in a simple array-of-buckets table. Capacity is usually kept proportional to n by resizing, so this is normally just called O(n).

Why is using a mutable object as a dictionary key risky in languages where hashing is based on the object's *contents* (unlike JavaScript's `Map`, which hashes objects by reference)?

If the hash comes from the object's fields, changing the object after insertion changes its hash, but the table doesn't move it. A later lookup hashes to a different slot than where the entry lives, so the entry becomes silently unreachable.

Why does a hash table with a well-chosen hash function and controlled load factor still occasionally show a few lookups taking longer than others, even without an attack?

By chance, even a good hash function puts some keys in the same slot or nearby probe positions. The birthday paradox means some collisions are expected long before the table is full, so a few lookups doing extra comparisons is normal.

How would you design a hash function for strings, at a high level, and why is a simple sum of character codes a poor choice?

A common approach is a polynomial rolling hash: treat the string as digits in some base p (s[0]*p^(n-1) + s[1]*p^(n-2) + ... + s[n-1]), then take it modulo the table size. Summing character codes ignores order, so anagrams like 'listen' and 'silent' hash the same, causing many needless collisions.

Scenario: you're building a cache that must evict the least-recently-used entry once it hits a size limit, and needs O(1) `get`/`put`. Why is a hash table alone not enough?

A hash table gives O(1) lookup by key but knows nothing about recency, so finding the least-recently-used entry means scanning everything: O(n). It needs an ordering structure alongside it, a doubly linked list.

What is the practical difference between a hash table's worst-case and average-case complexity, and why do interview answers usually default to quoting the average case?

The O(n) worst case needs unusually bad collisions: a poor hash function, adversarial input or extreme bad luck. With a good hash function and a bounded load factor, normal inputs behave as O(1), which is what you see in practice. So O(1) average is the useful number; O(n) worst case is the limit to be aware of.

What's the difference between a hash table's `capacity` and its `size`, and why does an implementation usually keep capacity a prime number or a power of two?

size is the number of stored entries; capacity is the number of slots. A prime capacity (with modulo hashing) or a power of two (with bitmask hashing) tends to spread common hash values more evenly, so a poorly mixed hash is less likely to crowd keys into a few slots.

Compare a hash table to a balanced binary search tree (like a red-black tree) as a dictionary implementation — what does each give up?

A hash table gives O(1) average lookup/insert/delete but O(n) worst case, no ordering, and no efficient range queries or min/max. A balanced BST gives O(log n) worst case for all three, keeps keys sorted, and supports range queries and ordered traversal, but is slower on average for a plain exact-key lookup.

Why would `for...in` over a plain JavaScript object used as a hash table be riskier than iterating a `Map`'s entries?

for...in also walks enumerable properties inherited through the prototype chain. If a prototype (or a library) added any, they mix in with your data unless you guard with hasOwnProperty or use Object.keys/entries. A Map only iterates entries you set.