Hashing in Python
Chapter 35: Hashing
5 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
The hash function: from a key to a bucket
A hash function turns a key into a number, and that number, divided by the number of buckets, leaves a remainder that says which bucket the key lives in.
Collisions, load factor and growing: why a dict is fast
A hash table keeps each bucket's chain of keys short by watching its load factor, keys ÷ buckets, and doubling the table when it gets too high.
Counting and grouping with a dict
Walk the items once and use a dict whose key says which group an item belongs to; the value is the count (counting) or the list of items (grouping).
Trading memory for time: the two-sum idea
As you walk the list, remember each number's position in a dict; for each new number x, the partner you need is target - x, and the dict says in O(1) whether you have already seen it.
Finding a word in a text: rolling hash and KMP
Rabin–Karp slides a window across the text, updating the window's hash in O(1) per step and checking letters only when it equals the pattern's hash; KMP builds a table that says, for each prefix of the pattern, the longest part that is both its start and its end, so after a mismatch the search continues without re-reading the text.