Hash table
An array of slots where a key is stored at the position given by hashing it, so finding a key means computing one hash and reading one slot. It exists because sorted structures cost a logarithm per lookup and most lookups do not need order at all.
What it costs
| Operation | Cost | Note |
|---|---|---|
| Lookup by key | O(1) average: 1 hash + 1–2 slot reads | Worst case O(n) if every key collides, which a good hash makes vanishingly rare. |
| Insert | O(1) average: 1 hash + 1 slot write | Occasionally O(n) when the table resizes and every key is rehashed into a bigger array. |
| Delete | O(1) average | With open addressing a deleted slot gets a tombstone so later probes keep walking past it. |
| Range scan / ordered iteration | Not supported | Keys are scattered by hash. Sort the keys yourself or use a tree or skip list. |
Memory: One slot per key divided by the load factor (how full the table is allowed to get). At a 0.75 load factor a million 16-byte keys with 8-byte pointers take about 32 MB: 24 bytes per entry plus a third again in empty slots.
Hash, mask, slot, and a collision chain
Each key is hashed to a 64-bit number, masked down to a slot index, and stored there. Two keys landing in the same slot form a short chain; a lookup compares stored keys until it matches.
How it works
- Pick a hash function that turns any key into a large number with the bits well mixed, so similar keys ("user:41", "user:42") land far apart. MurmurHash3 or xxHash for in-memory tables; never a plain checksum.
- Reduce the hash to an array index with hash mod table_size, or hash & (size - 1) when the size is a power of two, which is a single AND instruction.
- Write the key and value into that slot. When two keys hit the same slot (a collision), either store a short linked list of entries in the slot (chaining) or walk to the next empty slot and store there (open addressing).
- A lookup hashes the key, goes to the slot, and compares the stored key against the one asked for; with chaining it walks the list, with open addressing it probes forward until it finds the key or an empty slot.
- Track the load factor, the number of entries divided by slots. Past about 0.75 the probe chains get long, so allocate an array twice the size and reinsert every key into it. That one rehash costs O(n) but happens only every doubling, so the amortised cost per insert stays constant.
Why the shape is an array, not a tree
- Array indexing is one memory access with no pointer chasing, so a lookup is a few nanoseconds in cache and about 100 ns on a main-memory miss. A balanced tree over a million keys is 20 pointer hops.
- The price is order: a hash table cannot answer "the ten keys after K" or "all keys between A and B". Redis keeps a hash table for plain keys and a skip list beside it for sorted sets for exactly that reason.
Worked example
The connection registry for the chat app
- 100M users, 20M online at once. The registry maps user_id to the connection server holding that user’s socket: a hash table with 20M entries of an 8-byte user id and a 4-byte server id.
- Slots: 20M entries at a 0.75 load factor need 27M slots; round to 32M (a power of two, so the index is hash & 0x1FFFFFF). Each slot holds 12 bytes of payload plus 4 bytes of bookkeeping: 32M × 16 B = 512 MB. One Redis node, or a hash per shard.
- A message for Bob: hash "bob" to a 64-bit number (xxHash, about 10 ns), AND with the mask to get slot 19,443,210, read the slot, compare the key, return server C. One probe, roughly 100 ns on a memory miss. 500K messages per second cost well under one core.
- Bob reconnects to server D: the same hash finds the slot and the value is overwritten in place. Bob disconnects: the entry is deleted and, in Redis, the key simply expires if his heartbeat stops.
- The table grows from 16M to 32M slots when the 12-millionth user connects at the morning peak. Redis does this rehash incrementally, moving a few buckets per operation, so no single request sees the O(n) cost.
When it is the wrong choice
- You need ordered access: range scans, "next after K", top-N by key. Hashing destroys order; use a B-tree or skip list.
- The table must live on disk and be read in pages: random slots mean a page read per lookup with no locality, which is why on-disk hash indexes are rare and B-trees dominate.
- Keys are adversarial (user-supplied strings hashed with a predictable function): an attacker can make every key collide and turn O(1) into O(n). Use a seeded hash such as SipHash for untrusted input.
Interviewer follow-ups
Answer out loud before you open each one.
What is a load factor and why does it matter?
It is entries divided by slots. At 0.5 most probes hit on the first try; at 0.9 the average probe chain is several slots long and performance falls off sharply. Tables resize at a threshold, usually 0.7 to 0.75, trading memory for short chains.
Chaining or open addressing: which would you pick?
Chaining is simpler and tolerates high load factors because each slot can hold a list. Open addressing keeps everything in one array, which is cache-friendly and faster for small entries, but needs tombstones on delete and a lower load factor. Most language runtimes use open addressing; Redis uses chaining.
How does Redis resize a hash table without pausing?
It allocates the new table alongside the old one and moves one bucket per operation (and a few more per background tick), looking up keys in both tables until the move finishes. Every request pays a tiny extra cost instead of one request paying for the whole rehash.
Why does a hash table make a poor disk index?
Hashing scatters keys, so neighbouring keys live on unrelated pages and a range scan touches every page. A B-tree keeps neighbours together and needs only a few page reads per lookup anyway, so the constant-time advantage of hashing is not worth losing order on disk.
Where it shows up
- Building blocks
- Key → value at any scale · Cache the hot reads · Find which server holds a user · Drop duplicate events · Make retries safe · Collapse duplicate in-flight requests
- Problems
- Chat App (WhatsApp / Messenger) · Distributed Key-Value Cache (Redis / Memcached-like) · URL Shortener (TinyURL / bit.ly)