Hash maps and sets
If you learn one data structure for interviews (and for real code), make it the hash map: Python's dict, JavaScript's Map, Java's HashMap. It stores key → value pairs and finds any key in O(1) time on average. A set is the same idea with keys only. They turn countless O(n²) solutions into O(n) ones.
How hashing works
A hash function turns a key into a number. The map uses that number to pick a bucket in an internal array, so it can jump straight to the right place instead of searching:
- Two keys can land in the same bucket: a collision. Each bucket holds a short list (chaining); Python's dict instead probes other slots (open addressing).
- When the map gets too full (the load factor passes a threshold), it resizes and rehashes everything. That's occasional, so operations stay amortised O(1).
- Keys must be hashable (immutable): strings, numbers and tuples work; lists don't.
| Operation | Average | Worst case (everything collides) |
|---|---|---|
| Insert, look up, delete | O(1) | O(n) |
| Iterate over all items | O(n) | O(n) |
Since Python 3.7, dicts also remember insertion order.
Pattern 1: counting
Pattern 2: "have I seen this before?"
Two Sum, the most famous interview question: return the indexes of two numbers that add up to a target. Store each number's index; for every new number, check whether its complement was seen:
One pass, O(n), versus O(n²) for checking every pair.
First duplicate, and duplicates within k
Pattern 3: prefix sums + a hash map
How many contiguous subarrays sum to k? Keep counts of the running sums seen so far: a subarray ending here sums to k when running − k was a previous running sum.
O(n), and it works with negative numbers too, where a sliding window wouldn't.
Sets
Sets support fast membership tests and set algebra:
When not to use a hash map
- You need data in sorted order or range queries ("all keys between 10 and 20"): use a sorted structure (a balanced tree, or a sorted list with
bisect). - Memory is very tight: hash maps use extra space for their buckets.
- Keys are small integers in a known range: a plain list indexed by the number is simpler and faster.
Practice
- Write
is_isomorphic("egg", "add")→True,("foo", "bar")→Falseusing two dicts. - Return the
kmost frequent words in a text (useCounter). - Given a list of emails, count how many unique addresses there are after removing dots and anything after
+in the local part.
1.What is the average time to look up a key in a hash map?
2.Why can't a Python list be used as a dict key?
3.In the one-pass Two Sum, what does the dict store?