/ THE IDEA
A key identifies an entry, such as the text “theme”; its value might be “dark”. A hash function turns the key into a number. The table maps that number into its current storage positions. Because the table has limited positions, different keys can lead to the same starting position. A collision is that shared destination. An implementation resolves it by following a defined procedure, such as checking further positions or inspecting a group of entries. Equality checks distinguish the actual keys. Our example uses a simple forward-checking rule only to make the mechanism visible; production tables use more careful hashing and placement policies.
THE FORMAL IDEA
start = hash(key) mod M; then verify key equality
| M = number of table slots; mod means remainder after division. | | hash(key) = a repeatable integer computed from the key. A slot is a storage position, not proof that every entry found there has the requested key. |
|
RUN THE TINY EXAMPLE
Change one thing. Predict what happens.
Toy table: M = 5; invented hash(Ada) = 7 and hash(Bo) = 12. Both start at slot 2 because 7 mod 5 = 2 and 12 mod 5 = 2. Ada is stored at 2; Bo checks the mismatch and is stored at the next empty slot, 3. Change only requested key from Ada to Bo: lookup checks slot 2, rejects Ada, then matches Bo at 3.
|
The collision did not force the table to return the wrong value. Correctness came from comparing keys and using the same placement rule during insertion and lookup. Hashing supplied a promising starting point; equality supplied identity.
/ SO WHAT?
As more slots fill, detours can grow longer. A table may allocate more space and redistribute entries according to the new slot count. That resizing costs work at the time but helps keep later searches short. The physical position of an entry is therefore not a permanent identity that callers should rely on.
ONE CAVEAT |
| Expected fast lookup depends on suitable hashing and occupancy; worst cases can be much slower. The toy hashes and forward scan do not describe CPython’s exact implementation, and deleting entries needs rules that preserve later lookup paths. |
KEEP THIS
Hashing chooses where to begin, but key equality and collision-handling rules determine whether a lookup returns the correct entry.
|
NEXT: Why water speeds up inside a narrower pipe
|