Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 1

From Keys to Buckets

Trace how hash functions and modulo compression map immutable keys into fixed array indices in O(1) expected time, contrast dict and set semantics, and see where direct-address tables run out of memory.

Contentsand lesson path

What you will learn

  • Implement a hash map with separate chaining and load-factor-based resizing that passes randomized tests against dict.
  • Explain when hash operations degrade to O(n) and what makes a key hashable, including consistent __hash__ and __eq__ on custom classes.

Prerequisites: Complexity Analysis

01. Why it matters

In How a Python List Grows, you saw that indexing arr[i] by integer position runs in O(1) time, whereas checking "grace" in arr scans up to all n entries (O(n)). If an API validates a session token or username on every incoming request, linear scanning slows down proportionally as users grow—and keeping a sorted list for binary search still costs O(log n) per lookup plus O(n) element shifting on insertions.

Can you convert an arbitrary immutable key—such as a username, IP address, or coordinate tuple—into an integer array slot so lookups stay O(1) on average? That is what a hash table does. Understanding the two-stage pipeline from key to hash code to modulo bucket index also explains why Python dict (key-to-value map) and set (key-only membership collection) reject mutable keys such as list and dict.

02. From direct-address tables to hash compression

Suppose every key were a dense integer between 0 and 999. You could allocate a 1,000-slot list table and store key k directly at table[k]. That initial design—a direct-address table—gives true worst-case O(1) lookups with zero collisions, and when keys are dense integers in a small fixed range, it beats a hash table on both speed and memory.

The direct-address approach breaks down as soon as keys come from a huge or non-numeric universe, such as strings or 1,000 active 64-bit user IDs scattered across 0 .. 2^64 - 1. Allocating 2^64 slots would require exabytes of RAM, nearly all empty. A hash table stores those 1,000 active keys in roughly 2,000 buckets using two steps:

  1. Hash code: map key k deterministically to an integer h = hash(k). Equal keys must produce equal integers (k1 == k2 implies hash(k1) == hash(k2)).
  2. Compression: fold h into a valid bucket index 0 .. m - 1 via idx = h % m, where m is the bucket count.

For lookups to stay fast, a hash function needs four traits: it must be deterministic for equal keys, fast to compute (O(key_size), independent of table size n), sensitive to order and small edits (so "tea" and "eat" or "user_1" and "user_2" do not clump together), and roughly uniform across 0 .. m - 1.

Simplification boundary: our teaching function below multiplies weighted character codes (acc * 31 + ord(ch)). Real CPython hash() on str and bytes uses SipHash-1-3 with a fresh per-process random seed (sys.hash_info.algorithm == 'siphash13') so attackers cannot pre-compute colliding strings across restarts.

Text · mapping an arbitrary key into m = 8 buckets
key "ada"   ---> hash(key) = int ---> % 8 ---> bucket 6 ---> [ ("ada", val) ]
key "grace" ---> hash(key) = int ---> % 8 ---> bucket 0 ---> [ ("grace", val) ]
key "guido" ---> hash(key) = int ---> % 8 ---> bucket 6 ---> shares bucket 6!

03. Negative hash values, Python modulo and dict/set semantics

In CPython, hash(key) returns a signed integer (64-bit on 64-bit builds, or 32-bit on 32-bit builds), so negative hash codes are completely normal. In languages such as C or Java, % rounds toward zero and returns a negative remainder when h < 0 (for example -3 % 8 == -3), which crashes or reads memory before slot 0 unless you manually shift it back (((h % m) + m) % m). Python uses floor-division semantics instead: -3 // 8 == -1, and -3 == (-1) * 8 + 5, so -3 % 8 == 5. Whenever m > 0, h % m in Python always yields a valid slot index in 0 .. m - 1. Let us verify both negative modulo behaviour and polynomial rolling hashes in Python.

Python · deterministic rolling hash, anagram sensitivity, and modulo compression
def simple_string_hash(text: str) -> int:
    """Toy polynomial rolling hash for teaching bucket compression."""
    acc = 0
    for ch in text:
        acc = acc * 31 + ord(ch)
    return acc


m = 8
for name in ("ada", "grace", "linus", "guido"):
    h_toy = simple_string_hash(name)
    print(f"{name:<6} toy_hash={h_toy:<11} bucket={h_toy % m}")

print("anagram hashes:", simple_string_hash("tea"), simple_string_hash("eat"))
neg_hashes = [hash(-100), hash(-5), hash(-3), hash(0), hash(7), hash(19)]
print("sample hashes:", neg_hashes)
print("mod 8 results:", [h % 8 for h in neg_hashes])
Expected output
ada    toy_hash=96414       bucket=6
grace  toy_hash=98615224    bucket=0
linus  toy_hash=102977775   bucket=7
guido  toy_hash=98712326    bucket=6
anagram hashes: 114704 100184
sample hashes: [-100, -5, -3, 0, 7, 19]
mod 8 results: [4, 3, 5, 0, 7, 3]

Trace "ada" through simple_string_hash: 0 * 31 + 97 = 97, 97 * 31 + 100 = 3107, 3107 * 31 + 97 = 96414, and 96414 % 8 == 6. Both "ada" and "guido" yield bucket=6 even though their full hashes (96414 vs 98712326) differ—modulo % 8 compresses infinitely many integers onto 8 buckets, so collisions are inevitable. Look what happens if you shrink m from 8 to 2: half of all keys pile into bucket 0 and half into bucket 1, degrading lookups toward O(n). Notice also why multiplying by 31 matters: "tea" (114704) and "eat" (100184) produce distinct hashes, whereas simply summing ord(ch) would give every anagram the same hash before % m even ran.

In Python, both dict and set rely on this hash-and-compare pipeline. A dict stores unique keys mapped to values (d[k] = v), preserves insertion order (guaranteed in Python 3.7+), and supports O(1) expected lookups, inserts, and deletes; a set stores unique keys with no associated values (k in s) for fast membership checks and deduplication without preserving insertion order. Note what happens when you check k in d or d[k]: Python computes hash(k), inspects the candidate slot, and verifies key equality (==). Because lookup only checks the slots on the probe path chosen by hash(k), never the whole table, a key's hash must remain constant for its entire time inside the container—which is why immutable types (int, str, tuple of hashables) work as keys while mutable list, dict, and set objects raise TypeError.

When not to use a hash table: skip hashing when keys are dense integers in a tiny known range 0..999 (a flat list avoids hashing and collisions completely), when keys must be mutable objects whose contents change in place, or when your workload needs range queries (keys between "b" and "d"), min/max queries, or sorted traversal—because hashing scatters key order across buckets. For ordered queries, look ahead to Binary Search or Binary Search Trees.

04. Check your understanding

Practice check · 2 questions

Hashing and bucket mapping

Check how hash codes, equality and direct indexing behave.

Q1. What breaks in a hash table if a custom key type satisfies `k1 == k2` while `hash(k1) != hash(k2)`?
Q2. A high-throughput parser tracks seen ASCII byte values `0..255`. Why can `[False] * 256` beat a `set[int]` here?
Practice only: not graded, not saved, not evidence.

05. Apply it

In a Python 3.12 script, print hash(s) and hash(s) % 16 for 10 distinct words across two separate python3.12 runs. Verify that negative hash(s) values still produce % 16 indices in 0..15 in every run, while hash("ada") itself changes between runs because SipHash-1-3 uses a fresh random seed per process.

Next, see how tables handle colliding keys, tombstones, and growth in Collisions, Load Factor and Resizing.

06. Review prompt

Without looking back:

  1. Why do we hash and compress keys instead of always using a direct-address table?
  2. Why is hash(key) % m safe in Python even when hash(key) is negative, and why does acc * 31 + ord(ch) beat sum(ord(ch))?
  3. Name two situations where a hash table is the wrong choice compared to a flat array or a balanced search tree.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check