The magic behind instant lookups
โ Back to AlgorithmsA hash table stores keyโvalue pairs so you can look up any value instantly โ O(1) on average. In Python, the dict you already know is a hash table!
How? A hash function turns a key into a number that points straight to a slot in memory. No searching through items one by one โ it jumps right to the answer.
To find a name in a list, you might check every element โ O(n). A dict jumps directly to it โ O(1).
| Task | List | Dict / Set |
|---|---|---|
| Look up a value | O(n) | O(1) |
Check membership (in) | O(n) | O(1) |
| Add an item | O(1)* | O(1) |
A set is like a dict with keys but no values. It stores unique items and checks membership in O(1).
Hash tables make counting things effortless. This pattern appears in tons of problems:
.get(key, 0)It returns the current count, or 0 if the key isn't there yet โ perfect for "add one to the tally."
dict) give O(1) lookups via a hash function..get(key, 0) + 1.