Module 1 · Lesson 2 · ~25 min
Hash tables are the single most-used data structure in interview problems. Most people parrot "O(1) lookup" without understanding why, when it breaks, or what an interviewer is fishing for when they ask. This lesson is what nobody told you in the bootcamp.
You hand the coat-check attendant your jacket. They take a peek at it, decide "this jacket goes on hook 17," and hang it. When you come back, you give them your ticket. They glance at it, compute "ticket 47 → hook 17," reach to hook 17, hand you back the same jacket.
The trick: the attendant computes a small number from the ticket — the slot. They don't search every hook. They jump straight to the right one.
That "compute a small number" is the hash function. The hooks are the buckets. The whole arrangement is the hash table.
"hello", you get back something like 3502291412. Big random-looking number.3502291412 % 16 = 4. Bucket 4 it is.Try it. Add fruits one at a time. Two things to watch for:
Two different keys can hash to the same bucket. Has to happen if the keyspace is bigger than the bucket count (almost always). Real hash tables resolve collisions one of two ways:
Each bucket holds a list (or linked list) of entries. Lookup hashes to the bucket, then linearly walks the list looking for the matching key. This is what Python dict, Java HashMap, and Go map all use, with various sophistications.
If bucket k is taken, try k+1, then k+2, etc. (linear probing) or jump by quadratically growing offsets (quadratic probing). Used by some specialized implementations and CPython's set.
Both work. Both have the same average-case Big-O. The difference shows up in cache behavior and adversarial-input resistance.
| Operation | Average | Worst | Why worst is bad |
|---|---|---|---|
| Insert | O(1) | O(n) | If every key happens to hash to the same bucket, the bucket becomes a linked list of length n. |
| Lookup | O(1) | O(n) | Same — must walk the bucket's chain. |
| Delete | O(1) | O(n) | Same. |
| Resize | — | O(n) | When load factor crosses ~0.66, allocate a bigger array and rehash every key. Amortized O(1) per insert across many inserts. |
"Hash table operations are O(1)" is shorthand for "average case, assuming a decent hash function and inputs that aren't adversarial." Worst case is O(n). Senior interviewers will sometimes ask you to acknowledge this — it's a free signal that you understand the structure.
If an attacker can submit many keys that all hash to the same bucket, they degrade your O(1) hash to O(n) — and your O(n) algorithm to O(n²). This was a real DoS attack on web servers a decade ago.
The fix: randomized hashing. Python, Java, Ruby, and most modern languages seed their hash function with a random value chosen at process start. So an attacker who computed colliding keys for one process can't reuse them for the next one.
If you ever need deterministic hashing across runs, you have to opt in (e.g. PYTHONHASHSEED=0). Just knowing this exists puts you in the top 10% of senior candidates.
A key needs two properties:
Concretely:
int, str, tuple of hashables, frozenset). Lists and dicts are not.hashCode() and equals() consistently.If a problem involves "remember a (row, col) coordinate," a Python developer reaches for (row, col) as a tuple key. A JS developer needs a string like r + ',' + c because {[r, c]: x} stringifies to "r,c" by accident — and surprisingly often works, but you should know why.
A hash set is a hash table where you only care if a key is present. Same Big-O, half the memory, much-loved for "have I seen this before" problems.
# Find first duplicate — hash set version
def first_dup(arr):
seen = set()
for x in arr:
if x in seen: return x
seen.add(x)
return None
# O(n) time, O(n) space
// Find first duplicate — hash set version
function firstDup(arr) {
const seen = new Set();
for (const x of arr) {
if (seen.has(x)) return x;
seen.add(x);
}
return null;
}
// O(n) time, O(n) space
// Find first duplicate — hash set version
function firstDup(arr: number[]): number | null {
const seen = new Set<number>();
for (const x of arr) {
if (seen.has(x)) return x;
seen.add(x);
}
return null;
}
// O(n) time, O(n) space
Once you've internalized these five patterns, "use a hash table" will be one of the first three things you reach for in any optimization step.
def is_anagram(a, b):
if len(a) != len(b): return False
counts = {}
for ch in a:
counts[ch] = counts.get(ch, 0) + 1
for ch in b:
if ch not in counts: return False
counts[ch] -= 1
if counts[ch] < 0: return False
return True
# Or using Counter: return Counter(a) == Counter(b) — also O(n).
function isAnagram(a, b) {
if (a.length !== b.length) return false;
const counts = new Map();
for (const c of a) counts.set(c, (counts.get(c) || 0) + 1);
for (const c of b) {
if (!counts.has(c)) return false;
counts.set(c, counts.get(c) - 1);
if (counts.get(c) < 0) return false;
}
return true;
}
function isAnagram(a: string, b: string): boolean {
if (a.length !== b.length) return false;
const counts = new Map<string, number>();
for (const c of a) counts.set(c, (counts.get(c) || 0) + 1);
for (const c of b) {
if (!counts.has(c)) return false;
counts.set(c, counts.get(c)! - 1);
if (counts.get(c)! < 0) return false;
}
return true;
}