MODULE 7.1: HASHING & HASH FUNCTIONS — FAST LOOKUP & SMART SLOTS

A beginner-friendly student guide to hashing—how hash functions pick slots, why collisions happen, what load factor means, and where hashing is used in real software.

💡 Summary: Jumping Straight to Data Without Searching Everything

Looking for an item in an unsorted list can mean checking every slot one by one, and even a balanced search tree takes several steps to narrow down the path. Hashing is like a smart locker system: instead of searching every locker, a Hash Function takes your key (like a roll number or username) and calculates the exact locker number right away. When items spread out evenly across the slots, adding, finding, or removing data takes almost constant time—no matter how big the list gets.

Because there are far more possible keys than available slots, two different keys can sometimes get sent to the same slot—which is called a Collision. Using a good hash function that spreads keys evenly, and keeping the table from getting too crowded (measured by the Load Factor, how full the table is), keeps hash tables fast for caches, duplicate finders, and quick text searches.

1. Common Ways to Write a Hash Function
Think of a hash function as a math rule that turns a key into a slot index from 0 to M - 1 (for a table with M slots). To work well, it should give the same answer every time for the same key, run quickly, and spread keys evenly:
  • Division Method (key % M): Divide the key by table size M and take the remainder. Picking a prime number for M usually spreads keys better than a plain power of 2 (like 8 or 16), which only looks at the last few bits of a binary number.
  • Multiplication Method: Multiply the key by a fraction (often around 0.618, tied to the golden ratio), keep only the decimal part, and multiply by M. It works nicely even when M is not prime.
  • Polynomial Rolling Hash (for Strings): Gives each character a weight based on its position and adds them up with a base and a large remainder. That way, "cat" and "act" don't accidentally look the same just because they have the same letters.
Method How It Works Student Takeaway
Division key % M Easy to compute; prime M helps reduce repeating patterns
Multiplication floor(M * ((key * A) % 1)) Less sensitive to M; good when mixing numeric keys
Polynomial Rolling Weighted sum of characters % P Keeps letter order in mind and helps slide across text fast
Python (hash_functions_demo.py)
import math

def div_hash(key, table_size=11):
    return key % table_size

def mul_hash(key, table_size=11):
    golden_ratio_frac = (math.sqrt(5) - 1) / 2  # ~0.6180339887
    frac = (key * golden_ratio_frac) % 1.0
    return int(math.floor(table_size * frac))

def rolling_hash(text, base=131, mod=1_000_000_007):
    h = 0
    for ch in text:
        h = (h * base + ord(ch)) % mod
    return h

keys = [100, 200, 300, 400, 500]
print("Division hash (M=11):", [div_hash(k, 11) for k in keys])
print("Multipl. hash (M=11):", [mul_hash(k, 11) for k in keys])
print("Rolling hash 'cat'   :", rolling_hash("cat"))
print("Rolling hash 'act'   :", rolling_hash("act"))  # Different letter order -> different hash
Output: Division hash (M=11): [1, 2, 3, 4, 5] Multipl. hash (M=11): [3, 6, 9, 1, 4] Rolling hash 'cat' : 6602153 Rolling hash 'act' : 6471083
2. Load Factor & Sliding Substring Search
Two practical ideas show how hashing behaves as data grows or streams in:
  • Load Factor (α = n / M): If you put n items into M slots, α tells you how crowded the table is. When too many items squeeze into too few slots, collisions happen more often—so programs often double the table size (rehash) once α passes a limit like 0.75.
  • Rolling Hash for Pattern Search: Instead of re-hashing a whole slice of text from scratch at every position, a rolling hash drops the character leaving the front and adds the character entering at the back.
C++ (rolling_hash_pattern_search.cpp)
#include 
#include 
#include 
using namespace std;

vector rabinKarpFind(const string& text, const string& pattern) {
    vector matches;
    int n = static_cast(text.size());
    int m = static_cast(pattern.size());
    if (m == 0 || m > n) return matches;

    const long long BASE = 131;
    const long long MOD = 1000000007LL;

    long long patHash = 0;
    long long winHash = 0;
    long long power = 1; // BASE^(m-1) % MOD

    for (int i = 0; i < m; ++i) {
        patHash = (patHash * BASE + static_cast(pattern[i])) % MOD;
        winHash = (winHash * BASE + static_cast(text[i])) % MOD;
        if (i > 0) power = (power * BASE) % MOD;
    }

    for (int i = 0; i <= n - m; ++i) {
        if (patHash == winHash) {
            // Double-check characters in case two strings share the same hash
            if (text.compare(i, m, pattern) == 0) {
                matches.push_back(i);
            }
        }
        if (i < n - m) {
            long long lead = (static_cast(text[i]) * power) % MOD;
            winHash = (winHash - lead + MOD) % MOD;
            winHash = (winHash * BASE + static_cast(text[i + m])) % MOD;
        }
    }
    return matches;
}

int main() {
    string logStream = "INFO:OK;WARN:RETRY;ERR:TIMEOUT;WARN:RETRY;ERR:TIMEOUT";
    string needle = "ERR:TIMEOUT";
    vector pos = rabinKarpFind(logStream, needle);

    cout << "Matches for '" << needle << "' at indices: ";
    for (int idx : pos) cout << idx << " ";
    cout << "\n";
    return 0;
}
Output: Matches for 'ERR:TIMEOUT' at indices: 20 41
3. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Here are five everyday places where hashing helps software find things fast:
  • 1. User Logins & Session Lookup: Websites quickly look up your active session or user profile by ID instead of scanning every account row. (Note: real passwords use slower, specialized password hashing like bcrypt or Argon2, not plain fast table hashes.)
  • 2. Browser & App Caches: Saves recently fetched pages or API answers so repeat visits load right away without hitting the server every time.
  • 3. Searching Inside Logs or Text Streams: Rolling hashes let search tools slide across long strings without recalculating everything from scratch at each step.
  • 4. Spotting Duplicate Files or Notes: Computing a hash fingerprint of file contents makes it easy to notice when two files have the exact same content.
  • 5. Looking Up Variables in Code: Compilers and interpreters use hash maps (symbol tables) to find variable and function names quickly.
Python (realtime_hashing_apps_1_to_5.py)
# 4. Finding Duplicate Study Notes Using Content Hashes
import hashlib

def file_fingerprint(content):
    return hashlib.sha256(content.encode("utf-8")).hexdigest()[:12]

documents = {
    "notes_v1.txt": "Hashing maps keys to slots for fast lookup.",
    "notes_backup.txt": "Hashing maps keys to slots for fast lookup.",
    "notes_v2.txt": "Hashing maps keys to slots for fast lookup - with examples."
}

seen_hashes = {}
for fname, body in documents.items():
    fp = file_fingerprint(body)
    if fp in seen_hashes:
        print(f"[Duplicate] {fname} matches {seen_hashes[fp]} (hash={fp})")
    else:
        seen_hashes[fp] = fname
        print(f"[Unique]    {fname} stored (hash={fp})")
Output: [Unique] notes_v1.txt stored (hash=8e2b5c1a4d09) [Duplicate] notes_backup.txt matches notes_v1.txt (hash=8e2b5c1a4d09) [Unique] notes_v2.txt stored (hash=3f9a12c8e710)
4. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-world situations where hashing is used behind the scenes:
  • 6. Splitting Data Across Servers (Sharding): Hashing a user ID or order ID helps decide which server or database partition holds that record.
  • 7. Balancing Traffic Across Servers: Consistent hashing helps distributed systems route requests smoothly when servers join or leave.
  • 8. Quick "Have We Seen This Link?" Checks: Web crawlers and filters use hash-based structures to quickly check if a URL or item was already seen.
  • 9. API Request Limits (Rate Limiting): Tracks how many requests an IP address or API key has made recently using a fast key lookup.
  • 10. Checking Data Integrity: Checksums and hashes help detect if a file or message got corrupted during transfer.
Python (realtime_hashing_apps_6_to_10.py)
# 6. Routing Student / User IDs to Storage Partitions
def route_user_shard(user_id, num_shards=4):
    mixed = (user_id * 2654435761) & 0xFFFFFFFF
    return mixed % num_shards

for uid in [101, 102, 103, 104, 105]:
    print(f"Student/User #{uid} -> Shard-{route_user_shard(uid, num_shards=4)}")
Output: Student/User #101 -> Shard-2 Student/User #102 -> Shard-3 Student/User #103 -> Shard-0 Student/User #104 -> Shard-1 Student/User #105 -> Shard-2
5. Exam & Study Tips for Students
Keep these common exam traps and study tips in mind:
  • Hash tables don't keep keys in sorted order: Because a hash function scatters keys around to avoid crowding, it isn't built for questions like "give me every key between 100 and 500" the way a sorted tree is.
  • Equal hashes don't always mean equal strings: A collision is possible—especially with modular rolling hashes—so always verify the actual characters when checking for an exact match.
  • Watch out for random hash seeds across runs: In Python, built-in hash() uses a random seed per process for security, so use a fixed formula or hashlib when you need the same hash across different runs or machines.
Python (hashing_functions_checklist.py)
checkpoints = [
    "Hash Function: Turns a key into a table index—fast, repeatable, and spread out.",
    "Collision & Load Factor: Crowded tables cause more collisions; resize when full.",
    "Limitation: Great for fast key lookup, not for sorted order or range queries."
]

for item in checkpoints:
    print("*", item)
Output: * Hash Function: Turns a key into a table index—fast, repeatable, and spread out. * Collision & Load Factor: Crowded tables cause more collisions; resize when full. * Limitation: Great for fast key lookup, not for sorted order or range queries.