Hash Tables
How a hash table stores and finds values by key in constant time, how it handles collisions, and how interviewers expect you to use one.
On this page
A hash table stores key-value pairs and finds the value for a key in O(1) time on average, whether the key is a number, a string or a tuple. JavaScript calls it Map and Python calls it dict; the matching structure that stores only keys is a Set. You reach for one whenever a problem asks "have I seen this before?", "how many times has this appeared?" or "where is the value that goes with this one?".
Without a hash table, each of those questions means scanning a list from the start, which costs O(n) per question and O(n²) when you ask it once for every element. An array can look up by position in O(1), but only when the key is a small whole number. A hash table gives the same speed for keys such as strings, ids and coordinates.
How a hash table finds a key
A hash table is an array of buckets. A hash function turns a key into a whole number, and the same key always produces the same number. The table divides that number by the bucket count and keeps the remainder, which is the index of the bucket where the key belongs. Storing and finding a key both start with this calculation, so neither has to search the table.
Here is a deliberately weak hash function for strings: add up the character codes. For "owl" the codes are 111, 119 and 108, which add up to 338. With 5 buckets, 338 % 5 = 3, so "owl" is always stored in and looked up from bucket 3.
Collisions and chaining
There are far more possible keys than buckets, so two different keys sometimes map to the same bucket. This is called a collision. For example, "ant" adds up to 323, and 323 % 5 is also 3.
The most common rule is chaining. Each bucket holds a short list of [key, value] pairs. To store a key, the table hashes it, goes to its bucket, and either updates the pair if the key is already there or appends a new pair. To look up a key, it goes to the same bucket and compares keys along the list until one matches or the list ends. The trace below stores four animals and then looks up two keys.
b = (sum of char codes of key) % 5set: if key is in buckets[b]: update it else: add [key, value] to buckets[b]get: for each [k, v] in buckets[b]: if k == key: return v return not found- buckets
0 1 2 3 4 1The table starts with 5 empty buckets. Each row is a bucket, and each cell in a row holds one entry.
- buckets
0 1 2 3 ant:3 4 - key
- ant
- sum
- 323
- b
- 3
2Set ant to 3. The character codes add up to 97 + 110 + 116 = 323, and 323 % 5 = 3, so ant goes in bucket 3.
- buckets
0 1 2 3 ant:3 4 dog:5 - key
- dog
- sum
- 314
- b
- 4
3Set dog to 5. The codes add up to 314, and 314 % 5 = 4, so dog goes in bucket 4.
- buckets
0 1 2 cat:2 3 ant:3 4 dog:5 - key
- cat
- sum
- 312
- b
- 2
4Set cat to 2. The codes add up to 312, and 312 % 5 = 2, so cat goes in bucket 2.
- buckets
0 1 2 cat:2 3 ant:3 owl:1 4 dog:5 - key
- owl
- sum
- 338
- b
- 3
5Set owl to 1. The codes add up to 338, which gives bucket 3, and that bucket already holds ant, so this is a collision. Owl is not in the chain yet, so it is added after ant.
- buckets
0 1 2 cat:2 3 ant:3 owl:1 4 dog:5 - key
- owl
- b
- 3
- comparisons
- 1
6Get owl. Hashing the key again gives bucket 3, and the first entry there is ant, which does not match.
- buckets
0 1 2 cat:2 3 ant:3 owl:1 4 dog:5 - key
- owl
- b
- 3
- comparisons
- 2
- result
- 1
7The next entry is owl, which matches, so the lookup returns 1 after two comparisons.
- buckets
0 1 2 cat:2 3 ant:3 owl:1 4 dog:5 - key
- emu
- sum
- 327
- b
- 2
- comparisons
- 1
8Get emu. The codes add up to 327, and 327 % 5 = 2. Bucket 2 holds only cat, which does not match.
- buckets
0 1 2 cat:2 3 ant:3 owl:1 4 dog:5 - key
- emu
- result
- not found
9The chain ends without a match, so emu is not in the table. Each lookup compared the key with at most two entries instead of all four.
Real languages use a much better hash function than this one, but the structure is the same. The class below implements it.
class TinyMap {
constructor(size = 5) {
this.buckets = Array.from({ length: size }, () => []);
}
bucketFor(key) {
let sum = 0;
for (const ch of key) sum += ch.charCodeAt(0); // weak hash, for teaching
return this.buckets[sum % this.buckets.length];
}
set(key, value) {
const bucket = this.bucketFor(key);
for (const pair of bucket) {
if (pair[0] === key) { pair[1] = value; return; } // update
}
bucket.push([key, value]); // new key: add to the chain
}
get(key) {
for (const [k, v] of this.bucketFor(key)) {
if (k === key) return v;
}
return undefined; // not found
}
}class TinyMap:
def __init__(self, size=5):
self.buckets = [[] for _ in range(size)]
def bucket_for(self, key):
total = sum(ord(ch) for ch in key) # weak hash, for teaching
return self.buckets[total % len(self.buckets)]
def set(self, key, value):
bucket = self.bucket_for(key)
for pair in bucket:
if pair[0] == key:
pair[1] = value # update
return
bucket.append([key, value]) # new key: add to the chain
def get(self, key):
for k, v in self.bucket_for(key):
if k == key:
return v
return None # not foundKeeping the chains short
A lookup is fast only while the chains are short, and two things keep them short.
The first is a good hash function, which spreads keys evenly over the buckets. Adding character codes is a poor choice because every anagram gets the same sum, so "cat" and "act" always collide. Real hash functions mix every part of the key into the result, so similar keys end up in unrelated buckets.
The second is resizing. The load factor is the number of entries divided by the number of buckets. When it passes a limit, often around 0.75, the table allocates about twice as many buckets and inserts every entry again. Each entry is placed again because its remainder changes when the bucket count changes. This step costs O(n), but it happens only after the table has doubled, so inserts are still O(1) on average, in the same way as appending to a dynamic array.
With both in place a chain holds about one entry on average, so a lookup is O(1) on average. If every key lands in the same bucket, the table is one long list and a lookup compares against all n entries.
| Approach | Time | Space | Why |
|---|---|---|---|
| get, set, delete (average) | O(1) | O(n) for the table | Each chain holds about one entry on average. |
| get, set, delete (worst case) | O(n) | This happens when every key lands in the same bucket. | |
| Resize | O(n) once | A resize happens rarely, so inserts stay O(1) amortized. |
Variants
Open addressing
Chaining is not the only way to handle collisions. With open addressing there are no lists, and each bucket holds at most one entry. If the bucket for a key is taken, the table tries the next bucket, then the next, until it finds a free one. This is called linear probing. A lookup follows the same sequence and stops at a matching key or at an empty bucket, which proves the key is absent.
Open addressing uses less memory per entry and works well with the processor cache, but it has two problems. Entries that collide form clusters, so the table must be resized earlier, typically when it is about half to two thirds full. Deletion is also harder. If you simply empty the bucket of a deleted key, a later lookup for a key that was placed after it will stop at the empty bucket and wrongly report that the key is missing. The table has to leave a marker, often called a tombstone, so that lookups continue past it. Python's dict uses open addressing, while Java's HashMap uses chains.
Hash map and hash set
A hash map stores a value for each key. A hash set stores only keys and answers one question: is this key present? Use a set for "have I seen this?" and a map when you need to attach a count, an index or a list to the key.
Ordered maps
A hash table does not keep keys in sorted order, and it cannot answer questions such as "which key is the next one larger than this?" or "which keys fall between 10 and 20?" quickly. A map built on a balanced search tree, such as Java's TreeMap or C++'s std::map, answers them in O(log n) and keeps keys sorted, at the price of O(log n) for ordinary lookups. Choose the tree-based map when the problem needs order or ranges, and a hash table otherwise. The binary search trees lesson explains how it works.
When a hash table is not the right tool
If the keys are small integers or lowercase letters, a plain array indexed by the key is simpler, faster and needs no hashing: a count of 26 letters is an array of length 26. If the data is already sorted, two pointers or binary search can answer the same questions without the extra O(n) memory. If a problem needs the smallest or largest item repeatedly, use a heap, because a hash table has no way to find a minimum without scanning.
Replacing a search with a lookup
You will almost never write your own hash table, so the skill that matters is recognising when an inner loop can be replaced by one. Suppose you want to count how often each word appears in a list. The direct approach scans the whole list once for each word, which is O(n²). With a map you walk the list once and add one to the counter for each word.
function countWords(words) {
const counts = new Map();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1); // O(1) on average
}
return counts;
}
countWords(["red", "blue", "red", "green", "blue", "red"]);
// Map { "red" => 3, "blue" => 2, "green" => 1 }def count_words(words):
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1 # O(1) on average
return counts
count_words(["red", "blue", "red", "green", "blue", "red"])
# {'red': 3, 'blue': 2, 'green': 1}The same idea applies whenever an inner loop only searches. A map can remember "which values have I seen", "how many times", or "at which index", so each question costs O(1) instead of O(n). The cost is O(n) extra memory for the table.
Pitfalls
In the interview
Look for these signals in the problem statement. A phrase such as "find two values that satisfy a condition", "does any value appear twice", "count how many times", "group items that share a property" or "return the first one that repeats" usually means a hash table. So does a brute-force solution with a nested loop in which the inner loop only searches for something. The usual opening is to state the brute-force O(n²) solution, then say that a map from value to count or index removes the inner loop and brings the time down to O(n) with O(n) extra memory.
These are the follow-up questions to expect, with answers.
How does a hash table handle collisions?
There are two common ways. With chaining, each bucket holds a list of the entries that hash to it. With open addressing, a colliding key is stored in the next free bucket and lookups follow the same probe sequence. In both, the table keeps the load factor low by resizing so that collisions stay rare.
Why is a lookup O(1) on average but O(n) in the worst case?
Computing the hash and reaching the bucket takes constant time, and with a good hash function and a bounded load factor each bucket holds only a few entries. If many keys land in the same bucket, because of a bad hash function or input chosen to collide, a lookup has to compare against all of them. Java's HashMap limits the damage by turning a very long chain into a balanced tree.
What happens when the table gets full?
It resizes. When the load factor passes its limit, the table allocates roughly twice as many buckets and reinserts every entry, which costs O(n). Because the size doubles each time, this work spreads out to a constant amount per insert, so inserts are O(1) amortized, although a single insert occasionally takes O(n).
When would you use a tree-based map instead?
When the problem needs keys in sorted order, the nearest key above or below a value, or all keys in a range. A hash table cannot do these without scanning every key, while a balanced tree does them in O(log n) at the cost of slower ordinary lookups.
In a pair-sum problem, when do you add a number to the map?
Check the map for the complement first, and only then store the current number. If you store first, a number can match itself, so a target of 8 with the single value 4 would wrongly report a pair. This order also handles duplicates such as [4, 4], because the second 4 finds the first.
Can you solve it without the extra memory?
This is the usual follow-up to a map solution. For a pair-sum problem, sorting the array and using two pointers needs O(1) extra space but costs O(n log n) for the sort. The hash table is faster and the sorted version is smaller, so state both and say which one the constraints favour. When the array is already sorted, two pointers is better on both counts.
Using the sum-of-character-codes hash with 5 buckets, which key always lands in the same bucket as "cat"?
A badly chosen hash function sends all n keys to the same bucket. What does a lookup cost now?
A loop over n orders checks bannedIds.includes(order.customerId), where bannedIds is an array of n IDs. How do you make the whole check O(n)?
A problem asks for the smallest key that is larger than a given value, repeated many times. Which structure fits?
What to practise next
Solve Matching Receipts, where the obvious answer checks every pair and a map finds each partner in one step, and Crawler Seen Pages, which is a direct use of a set. When the data is sorted, Two Pointers often avoids the map and its memory.