C.W.K.
Stream
Lesson 06 of 06 · published

When Hashing Betrays You

~11 min · hashing, limits, trees-preview

Level 0Curious Beginner
0 XP0/85 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete
"Hashing feels like a cheat code, so it's tempting to use it for everything. But it buys you one specific thing — instant point lookup — at the cost of another: any sense of order. Knowing that line is the lesson."

The Big Blind Spot: No Order

A hash map scatters keys by their hash, which is deliberately unrelated to their value. That's great for "is this exact key present?" and useless for anything about order. You cannot ask a hash map: "give me the smallest key," "all keys between 10 and 20," or "the next key after this one" — without dumping everything and sorting (O(n log n)), which defeats the purpose. (Python's dict preserves insertion order, but that's not sorted order — don't confuse the two.) The moment your problem needs ordering or range queries, hashing is the wrong tool, and you reach for a tree — which is exactly where the next track goes.

The Other Betrayals

  • Worst-case O(n). If an attacker can craft keys that all collide, every operation degrades to a linear scan — a real denial-of-service called hash flooding. It's why Python randomizes string hashes per process (the PYTHONHASHSEED salt from earlier): so an attacker can't precompute a colliding key set.
  • Mutable keys corrupt the map. You can't use a list as a key, and you mustn't mutate an object after using it as one — change it and its hash changes, and the map can never find it again. Immutability isn't a Python quirk here; it's a correctness requirement.
  • Memory overhead. The empty slots that keep lookups fast also cost memory. For small, dense integer keys, a plain array (indexed directly) can beat a dict on both speed and space.
Hashing gives O(1) point lookup but throws away order. Need 'smallest', 'in range', 'sorted', or 'next-larger'? That's a tree, not a hash. Hashing also has an O(n) worst case (collisions), forbids mutable keys, and trades memory for speed. It's powerful, not universal.

The Deeper Lesson: No Universal Structure

This is the through-line of the whole quest, surfacing again: there is no one structure that wins at everything. The array trades insertion for indexing; the linked list trades indexing for splicing; the hash map trades order for instant lookup. Each is the right abstraction for a kind of access. Mastery isn't memorizing the structures — it's reading a problem and hearing which trade it's asking for. "I need fast lookup AND sorted order" is the problem statement that sends you from this track into the next one.

Pippa's Confession

Once I'd fallen in love with dicts, I tried to use one for a leaderboard that constantly needed "top 10 by score" and "everyone between rank 50 and 60." It was a disaster of repeated full sorts. Dad just said: "Hashing has no order. You want a tree." That sentence drew the boundary for me: the hash map is my reflex for point lookups, but the instant a problem whispers 'order' or 'range,' I hand it to a tree. The next track is that handoff.

Code

No order, no mutable keys, salted hashes·python
# 1) A dict preserves INSERTION order, not SORTED order.
d = {}
for k in [5, 1, 9, 3]:
    d[k] = k * 10
print(list(d))            # [5, 1, 9, 3] — insertion order, NOT sorted
print(sorted(d))          # [1, 3, 5, 9] — and sorting is O(n log n) each time
# 'smallest key', 'keys in [2, 6]', 'next key after 5' all require sorting first.
# If you need those a lot, a hash map is the wrong structure -> use a tree.

# 2) Mutable objects can't be keys (and mustn't be mutated if they were).
try:
    bad = {[1, 2]: "x"}   # a list is unhashable
except TypeError as e:
    print("TypeError:", e)   # unhashable type: 'list'

# 3) Hash randomization (run twice in fresh processes -> different numbers).
print(hash("pippa"))      # salted per-process; thwarts crafted-collision DoS

External links

Exercise

For each, say whether a hash map (dict/set) is the right structure or whether you need something ordered: (1) 'is this email already registered?', (2) 'give me all orders between two dates', (3) 'count visits per page', (4) 'what's the next-highest score above mine?'. For the ones that fail, name what ordering capability the hash map lacks.
Hint
(1) and (3) are perfect for a hash (exact lookup, counting). (2) and (4) need ORDER/RANGE — a hash map can't give 'between' or 'next-higher' without a full sort, so they call for a tree (or sorted structure). That's your bridge into the Trees track.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.