--- title: 'Hash Tables' 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.' --- ## The idea 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*. How? A hash function turns your key into a slot number. Same key → same slot, every time. Lookup is O(1). ## The picture ```mermaid flowchart LR K1["'apple'"] --> H["Hash
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"] style H fill:#1565c0,color:#fff ``` ## Three jobs it does 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