Hash Table
A hash table maps keys to bucket locations using a hash function. It aims for very fast average lookup, insertion and deletion.
Start with this mental model
A hash table maps keys to bucket locations using a hash function. It aims for very fast average lookup, insertion and deletion.
How it works, without unnecessary jargon
The hash function converts a key into an index-like value.
Different keys may collide, so the implementation needs a collision strategy such as chaining or open addressing.
Read the algorithm as a sequence of decisions
Hash the key.
Map the hash to a bucket.
Resolve collisions and compare actual keys.
A user id can be hashed to a bucket; the bucket then stores or finds the actual user entry.
class HashTable {
constructor(size = 16) {
this.buckets = Array.from({ length: size }, () => []);
}
hash(key) {
let h = 0;
for (const ch of String(key)) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return h % this.buckets.length;
}
}Do not memorize the syntax. Follow the state that changes on each line and connect it to the invariant described above.
avg O(1), worst O(n)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
Good fit
- Choose it when its dominant operations match your workload.
- Compare memory overhead as well as Big-O.
What usually goes wrong
- Calling average O(1) a guaranteed worst-case O(1).
- Ignoring key equality and collision handling.
A professional answer shape
Explain average O(1), collisions, load factor and resizing. Those details distinguish a strong answer from 'it is just a key-value map'.
What problem does Hash Table solve?
A hash table maps keys to bucket locations using a hash function. It aims for very fast average lookup, insertion and deletion.
What should I mention about complexity?
Its typical cost here is avg O(1), worst O(n), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
What is the most common mistake?
Calling average O(1) a guaranteed worst-case O(1).