Hash usage
easy 16 minHash maps and hash sets find a key by computing where it lives instead of searching for it, so insert, lookup and delete cost O(1) on average.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Compute where it lives, do not search for it.
A magic library. Every book title goes through a spell (the hash function) that turns it into a shelf number. The shelves (buckets) each have a hook to hang several books when two titles land on the same shelf. To find a book you cast the spell, walk straight to that shelf and check the few books hanging there. No need to visit every shelf: that is O(1) on average.
Cheat sheet
- Insert, lookup, delete
- O(1) avg, O(n) worst
- len(d)
- O(1), a stored count
- Iterate, clear, copy
- O(n)
- Value search
- O(n) scan of d.values()
- Valid keys
- hashable: int, str, tuple, frozenset
- Counting
- Counter or d.get(k, 0) + 1
- Grouping
- defaultdict(list), canonical key
- Two Sum, prefix sums
- check first, then store
- Dict order
- insertion order, never sorted
Spot it when you see
- Seen before, duplicate, visited, unique: a set.
- How many, frequency, most common, majority: Counter.
- Pair that sums to a target, index of a value: a value-to-index dict.
- Group by, anagrams, same pattern: defaultdict(list) with a canonical key.
- Subarray sum equals k, especially with negatives: prefix sums in a dict.
- The same expensive call repeats: a cache dict or lru_cache.
Tricks that stick
- HASH: Hash function, Array of buckets, Store key-value pairs, Handle collisions.
- Rhyme: hash the key to find the spot, mod by size, that's what you've got; collision? chain them in a row; O(1) average, watch it go.
- Inner loop that searches? Replace it with a dict lookup.
- Check, then store: the complement must come from an earlier element.
- Seed the prefix map with zero seen once.
- Set for yes or no, dict for what goes with it, Counter for how many.
Do not forget
- Using a list as a key: unhashable; use a tuple.
- count[x] += 1 on a missing key raises KeyError.
- Storing before checking lets an element pair with itself.
- d.get(k) returns None both for a missing key and for a stored None.
- Deleting keys while iterating raises RuntimeError: loop over list(d).
- Reading a missing key from a defaultdict inserts it.
- Assuming O(1) always: the worst case is O(n), and the dict costs O(n) space.