2026-08-17 14:19:02 -04:00
---
2026-08-20 13:37:21 -04:00
title: 'Hash Tables'
2026-08-17 14:19:02 -04:00
description: 'In algorithms, arrays and strings are very similar. They are both ordered collections of elements. The difference is that arrays are mutable, while strings are immutable.'
---
2026-08-20 16:04:24 -04:00
## The idea
2026-08-17 14:19:02 -04:00
2026-08-20 16:04:24 -04:00
A hash table is like a helpful grocery clerk.
You say "avocado". She tells you the price at once.
She does not walk the aisles. She just *knows*.
2026-08-17 14:19:02 -04:00
2026-08-20 16:04:24 -04:00
How? A hash function turns your key into a slot number.
Same key → same slot, every time. Lookup is O(1).
2026-08-17 14:19:02 -04:00
2026-08-20 16:04:24 -04:00
## The picture
2026-08-17 14:19:02 -04:00
2026-08-20 16:04:24 -04:00
```mermaid
flowchart LR
K1["'apple'"] --> H["Hash<br/>function"]
K2["'milk'"] --> H
K3["'avocado'"] --> H
H --> S0["Slot 0: milk → 1.49"]
H --> S1["Slot 1: apple → 0.67"]
H --> S2["Slot 2: avocado → 1.99"]
2026-08-17 14:19:02 -04:00
2026-08-20 16:04:24 -04:00
style H fill:#1565c0,color:#fff
```
2026-08-17 14:19:02 -04:00
2026-08-20 16:04:24 -04:00
## Three jobs it does
2026-08-17 14:19:02 -04:00
2026-08-20 16:04:24 -04:00
1. **Membership** — "have I seen this before?"
2. **Frequency** — "how many times?"
3. **Mapping** — "what goes with this?"
## Membership (LC 217 — Contains Duplicate)
```python
def contains_duplicate(nums: list[int]) -> bool:
seen = set()
for n in nums:
if n in seen:
return True
seen.add(n)
return False
```
## Frequency (LC 242 — Valid Anagram)
```python
from collections import Counter
def is_anagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
return Counter(s) == Counter(t)
```
## Key design (LC 49 — Group Anagrams)
Sometimes the trick is *what you use as the key*.
"eat", "tea", "ate" all sort to "aet". Sorted string = group key.
```mermaid
flowchart LR
A["eat"] --> K["key: 'aet'"]
B["tea"] --> K
C["ate"] --> K
K --> G["group: [eat, tea, ate]"]
style K fill:#1565c0,color:#fff
```
```python
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]:
groups = defaultdict(list)
for s in strs:
key = "".join(sorted(s))
groups[key].append(s)
return list(groups.values())
```
## Complexity
| | Average | Worst |
|---|---|---|
| Lookup / insert / delete | O(1) | O(n) |
Worst case comes from collisions. Interviews treat it as O(1).
## Close-out ritual
Before you submit, say out loud:
1. Time and space complexity.
2. One edge case trace: empty input, all same element, or key collision on your key design.
## Plan problems
**A-set:** LC 217 · 242 · 1 · 49 · 347
**B-set:** LC 383 · 205 · 128 · 290