Hashing & Hash Tables
The interview workhorse structure end-to-end: how hash maps and sets deliver average O(1) lookups, and everything that can go wrong along the way. Interviewers probe hash tables constantly because nearly every coding problem leans on them and their guarantees are easy to overstate.
part ofData structures & algorithmsoverview, primer and where to startread it →on this pageshowhide
explore
- Hash Functions & Key Design12 questions
- Hash Function Properties5 questions
- Equality & Hash Contract4 questions
- Hashing Mutable Keys3 questions
- Collision Resolution12 questions
- Separate Chaining4 questions
- Open Addressing & Probing4 questions
- Deletion & Tombstones4 questions
- Load Factor & Resizing8 questions
- Load Factor3 questions
- Resizing & Rehashing Cost5 questions
- Hash Maps & Sets in Practice8 questions
- Hash Map vs Hash Set Usage4 questions
- Production Hash Map Designs4 questions
- Guarantees & Pitfalls12 questions
- Expected vs Worst-Case Complexity4 questions
- Adversarial Collisions4 questions
- Iteration Order & Its Traps4 questions
- Alternatives & Cousins13 questions
- Ordered Tree Maps4 questions
- Linked-Hash Maps & LRU Caches4 questions
- Bloom Filter Idea5 questions
- Computer Scienceskillanchors this topic
- Data Structures & Algorithmsskillanchors this topic
- AI & Data Scientistrole
- AI Engineerrole
- AI Red Teamingrole
- Android Developerrole
- Backend Developerrole
- Blockchain Developerrole
- Cyber Security Expertrole
- Data Analystrole
- Data Engineerrole
- DevOps / SRE Engineerrole
- DevSecOps Engineerrole
- Forward Deployed Engineerrole
- Frontend Developerrole
- Full Stack Developerrole
- Game Developerrole
- Java Backend Developerrole
- Java SDETrole
- Kotlin Backend Developerrole
- MLOps Engineerrole
- Machine Learning Engineerrole
- Network Engineerrole
- PostgreSQL DBArole
- QA Engineerrole
- Software Architectrole
- iOS Developerrole
questions
65 · 6 sectionsWhy must two hash-table keys that compare equal also produce the same hash value?
basics
~20 sHash tables find the bucket by hash first and only then compare keys for equality. If equal keys hash differently, a lookup probes the wrong bucket, so a stored entry is never found and a set can silently hold duplicates.
What happens to a hash-table entry when the key object's fields change after insertion?
basics
~20 sNothing moves. The entry stays in the bucket chosen from the key's old hash value, while later lookups hash the new field values and probe elsewhere. The entry is stranded: unreachable by lookup, still occupying the table.
Why must a hash function be deterministic, and what breaks when it mixes in state outside the key?
basics
~20 sA hash function must return the same value for the same key contents every time, because a table locates an entry only by recomputing its bucket. Mix in a counter, a clock reading, or an object's memory address and stored entries become unreachable.
Which hash-function property keeps near-identical keys like ORD-1041 and ORD-1042 out of one bucket region?
basics
~20 sThe avalanche property: changing one bit of the key should flip about half the output bits, so structured keys land in unrelated places. Without it, a family of similar keys maps into a narrow band of hash values and fills only a handful of buckets.
A currency key type treats 100 cents and 1.00 dollars as equal after normalization — what does that require of its hash function?
basics
~20 sThe hash must be computed from the same normalized form the equality check compares — for example total cents — so every representation that compares equal hashes identically. Hashing the raw amount-and-unit fields lets equal keys hash apart, and lookups silently miss.
In a linear-probing hash table, how does a lookup find a key that collided when it was inserted?
basics
~20 sLinear probing puts a colliding key in the next free slot, so lookup replays that walk: start at the home slot and step forward comparing keys, stopping only at an empty slot, never at the first non-matching key.
In separate chaining, what happens when two keys hash to the same bucket, and what does a lookup then cost?
basics
~20 sBoth keys stay: the bucket holds a list, and the new entry is linked into that list. A lookup indexes the bucket in constant time, then walks the chain comparing full keys, so its cost grows with the chain's length.
In an open-addressed hash table, why does deleting a key by just emptying its slot break later lookups?
basics
~20 sEmptying the slot cuts a probe path. A lookup walks forward from the home slot and stops at the first empty slot, so a key that collided and landed past the hole is now reported missing even though it is still stored.
In separate chaining, why is expected lookup cost 1 + load factor rather than flatly O(1)?
basics
~20 sLoad factor is entries divided by buckets — under uniform hashing, exactly the expected chain length. A lookup pays a constant-time bucket index plus a walk of that many nodes, so cost is 1 + load factor, constant only because resizing bounds it.
How must insert and lookup treat a tombstone slot differently in an open-addressed hash table?
basics
~20 sA lookup must walk straight past a tombstone and stop only at a truly empty slot. An insert may reuse the first tombstone it sees, but only after probing on to confirm the key is not already stored further along.
A hash table holds 12,000 SKU entries in 16,384 buckets — what is its load factor, and does that value mean lookups are collision-free?
basics
~20 sLoad factor is entries divided by buckets: 12,000 over 16,384 is about 0.73. It measures average occupancy, not collision-freedom. With a good hash, roughly half those buckets sit empty and thousands of keys already share a bucket with someone.
When a hash table doubles its bucket array, why must every existing entry be re-bucketed?
basics
~20 sA key's bucket index is derived from its hash reduced by the table size, so changing the size changes where most keys belong. Copying buckets across unchanged would leave entries in slots that lookups no longer probe.
Why do production hash tables grow at roughly 0.6-0.75 occupancy instead of waiting until every bucket is used?
basics
~20 sBecause operation cost rises with occupancy long before a table fills. Growing at 0.6-0.75 spends spare bucket slots — cheap next to a stored entry — to keep chains and probe sequences short on every lookup.
Why is insertion into a growth-doubling hash table amortized O(1) when one insert rehashes everything?
basics
~20 sBecause doubling makes resizes exponentially rarer, so the total re-bucketing work across n inserts stays under about 2n and averages to a constant per insert over the whole sequence. It never promises that any individual insert is cheap.
Before bulk-loading five million records into a hash table, how do you choose its initial capacity?
basics
~20 sDivide the expected entry count by the target load factor and round up: five million records at a 0.75 growth threshold needs about 6.7 million buckets. Sizing to five million buckets exactly still triggers a resize.
When do you reach for a hash set instead of a hash map, and what does that choice signal?
basics
~20 sReach for a hash set when membership is the only fact you need, and a hash map when every key must carry data with it. A crawler tracking already-fetched addresses wants a set; a document indexer counting how often each word appears needs a map from word to count.
Why does storing each scanned value's index in a hash map find a matching pair in one pass?
basics
~20 sBecause for each record you can compute the partner you need and ask the map whether it has already been seen, in expected constant time. That replaces the inner loop of a nested scan, turning O(n^2) comparisons into one O(n) pass that trades O(n) memory for the speedup.
Why do production hash tables pick power-of-two capacities with bit masking over prime-modulo sizing?
basics
~20 sMasking with a power-of-two capacity turns the index step into a single bitwise AND instead of a division, and doubling splits each bucket cleanly. Prime sizing exists to blend weak hash bits; masked tables buy that with an explicit mixing step.
How is a hash set usually implemented on top of a hash map engine, and what does an entry store?
basics
~20 sA hash set is normally the same hash table with the value half unused: each entry holds the key and its cached hash, and a membership test is an ordinary lookup reporting found or not found.
Why does a one-pass seen-set beat sorting for finding the first repeated check-in badge?
basics
~20 sSorting answers a different question: it destroys arrival order, so "first repeat" stops being defined, and it costs O(n log n). A one-pass seen-set tests membership before each insert, reports the earliest repeated badge in O(n) expected time, and stops the moment it finds one.
Why is hash-table lookup called expected O(1) rather than simply O(1)?
basics
~20 sHash-table lookup is constant time only on average, assuming keys spread evenly across buckets. When many keys land in the same bucket the lookup walks that bucket instead, so the worst case is O(n) in the number of stored entries.
Why does a plain hash map make no promise about iteration order?
basics
~20 sIteration walks the internal bucket array from the first slot to the last, so the order falls out of each key's hash value and the table's current capacity. Nothing in that arrangement records when a key arrived, and no implementation commits to keeping it.
In a chained hash table, why does inserting n colliding keys cost quadratic time?
basics
~20 sEvery insert first scans its bucket to check whether the key is already present. When all n keys share one bucket, the k-th insert walks k-1 nodes, so the total is 1+2+...+(n-1), which is Theta(n squared).
Insert into a growing hash table is amortized O(1) — what does that promise, and what does it not?
basics
~20 sAmortized O(1) promises any sequence of n inserts costs O(n) in total, so the per-insert average is constant. It does not promise a single insert is cheap: the one crossing the growth threshold re-places every entry in linear time.
Why doesn't a hash map's expected O(1) lookup protect a service whose keys come from the client?
basics
~20 sExpected O(1) assumes keys were not chosen against the hash function. A client who can determine that function submits many keys that land in one bucket, so every insert and lookup there becomes a linear scan.
In a bloom filter, what does a 'yes' answer guarantee and what does a 'no' answer guarantee?
basics
~20 sA bloom filter's 'no' is certain: that item was never added. Its 'yes' means only 'probably present' — a fraction of queries for items that were never added still come back positive. Negatives are facts, positives are hints.
In an O(1) LRU cache, why isn't a hash map alone enough, and what does the doubly linked list add?
basics
~20 sThe hash map gives O(1) lookup from key to node but knows nothing about recency. The doubly linked list orders nodes by last use, so the eviction victim sits at a known end and unlinking it costs O(1).
What does an ordered map give you that a hash map does not, and what do you pay for it?
basics
~20 sAn ordered map keeps its keys in sorted order, so it supports in-order iteration, range scans between two keys, and nearest-key lookups. You pay O(log n) on every insert, lookup and delete instead of a hash map's expected O(1).
Where do a bloom filter's false positives come from, given that it stores only bits?
basics
~20 sFalse positives come from the union of everything already inserted. A never-added element tests positive when all of the positions it checks happen to be set — each possibly by a different element. No two keys need to share a hash value.