Foundations, Hash Functions & Load Factor
Universal hashing, avalanche effect, MurmurHash/xxHash principles, modulo prime bucket sizing, and load factor threshold theorem.
Topics Covered:
35. Hashing Principles & Direct Address Table Comparison • 36. Hash Functions & Uniform Distribution • 37. Collisions, The Birthday Paradox & Load Factor ()
Direct address tables offer constant-time retrieval by assigning every possible key a distinct physical array index, but demand catastrophic memory allocations when key universes are sparse. Hashing bridges this efficiency gap by compressing vast key spaces into compact array bounds through deterministic mathematical transformations. This chapter examines the Direct Address Dilemma, Simple Uniform Hashing Assumptions (SUHA), division and multiplication hash generators, polynomial rolling hashes for strings, the mathematical inevitability of collisions under the Birthday Paradox, and load factor () thresholds for dynamic rehashing.
Learning Objectives
#- Contrast direct addressing with compact hash tables and quantify the memory savings achieved across sparse key spaces.
- Formalize the Simple Uniform Hashing Assumption (SUHA) and evaluate the mathematical properties of division, multiplication, and polynomial rolling hash functions.
- Prove why hash collisions are mathematically unavoidable using Dirichlet's Pigeonhole Principle.
- Derive the Birthday Paradox collision threshold and explain why collisions occur far earlier than intuition suggests.
- Calculate the load factor and define dynamic table resizing (rehashing) triggers to preserve expected amortized bounds.
Topic 35: Hashing Principles & Direct Addressing
#1. Conceptual Architecture: The Direct Address Dilemma
In an ideal computational model, data retrieval executes in time by using the search key directly as an array index. This pattern is known as Direct Addressing.
The Direct Addressing Dilemma
Suppose an enterprise needs to store employee profiles indexed by a 9-digit Social Security Number (SSN: 000-00-0000 to 999-99-9999):
- Universe of Keys (): Contains possible keys ().
- Direct Address Table: Requires allocating a contiguous array of pointers. At 8 bytes per pointer, this demands of RAM!
- Sparsity Reality: If the company employs only workers, of the allocated memory sits permanently empty and wasted.
The Hashing Resolution
Rather than allocating memory for every conceivable key in universe , allocate a compact table of size (e.g., slots, requiring mere kilobytes of RAM). A deterministic mathematical function , called a Hash Function, maps keys into table index slots:
| Key Category | Example Raw Key | Hash Transformation | Assigned Slot | Allocation Impact |
|---|---|---|---|---|
| Active Employee 1 | 248-10-8914 | Slot 914 | Mapped to valid index | |
| Active Employee 2 | 512-40-1002 | Slot 2 | Mapped to valid index | |
| Active Employee 3 | 881-99-8914 | Slot 914 | Collision with Employee 1! |
Because , multiple keys will occasionally map to the same slot. Handling this gracefully is the core focus of hashing architecture.
Topic 36: Hash Functions & Uniform Distribution
#1. Desirable Properties of Production Hash Functions
#- Strict Determinism: For any identical key , must evaluate to the exact same integer every time across the process lifecycle.
- Simple Uniform Hashing Assumption (SUHA): Every key is equally likely to hash into any of the slots, independently of where any other key has hashed:
- Computational Efficiency: Evaluates in time for fixed-width numeric keys and time for strings of length .
- The Avalanche Effect: Flipping a single bit in the input key should alter roughly of the bits in the output hash code, preventing clustered hash values for sequential keys.
2. Classic Hash Function Algorithms
#A. The Division Method
B. The Multiplication Method (Knuth's Golden Ratio Method)
- Advantage: The choice of table size is not critical; it functions effectively even when is chosen as an efficient power of two ().
C. Polynomial Rolling Hash for Strings
A string is treated as a polynomial where character code units are coefficients evaluated at base :
Where:
- : A prime roughly equal to alphabet size (e.g., for lowercase English; for mixed-case ASCII).
- : A large prime modulus (e.g., or ) to bound integer values and prevent overflow.
FUNCTION PolynomialStringHash(S: String, p: Integer = 31, m: Integer = 1000000007) -> Integer:
hashVal <- 0
pPower <- 1
for each char c in S:
// Convert char to 1-based index ('a' -> 1, 'b' -> 2, ...)
charVal <- ASCII(c) - ASCII('a') + 1
hashVal <- (hashVal + charVal * pPower) mod m
pPower <- (pPower * p) mod m
return hashValTopic 37: Collisions, The Birthday Paradox & Load Factor ()
#1. The Inevitability of Collisions: The Pigeonhole Principle
#By Dirichlet's Pigeonhole Principle, if items are placed into containers and , at least one container must hold more than one item.
Because any realistic universe of keys vastly exceeds the physical table capacity (), collisions are mathematically guaranteed to occur. A collision occurs whenever:
2. The Birthday Paradox & Collision Likelihood
#How many randomly chosen people must gather in a room before the probability that at least two share a birthday exceeds ?
While common intuition guesses people (half of 365 days), the mathematical answer is just 23 people!
Formal Mathematical Derivation:
Let be the number of inserted keys and be the number of hash table slots. The probability that all keys hash into distinct slots (zero collisions) is:
Applying the standard Taylor series approximation for small :
To find the number of keys where the collision probability reaches ():
Collision Threshold by Table Size
| Table Capacity () | 50% Collision Threshold (
M834 80h400000v40h-400000z"/>) | Percentage of Table Utilized | | :---: | :---: | :---: | | (Days in Year) | | | | | | | | | | | | | | |
📌 Architectural Lesson:
In any hash table of size , collisions begin to occur after roughly insertions! Collision resolution is not an exceptional edge case; it is the central operational reality of every hash table.
3. The Load Factor () & Rehashing Dynamics
#The Load Factor measures the average occupancy density of the hash table:
Impact of on Collision Resolution Paradigms
| Property | Separate Chaining | Open Addressing (Probing) |
|---|---|---|
| Theoretical Range | ( can exceed 1.0) | (Strictly bounded by ) |
| Average Bucket Length | Exactly | Not applicable (all elements stored in array) |
| Expected Search Time | Unsuccessful: , Successful: | |
| Standard Resize Trigger |
Dynamic Rehashing
When exceeds the predefined threshold:
- Allocate a new backing array with approximately double capacity (, ideally the next prime number).
- Re-compute for every existing element and insert into the new table.
- Deallocate the old table.
Because dynamic doubling occurs geometrically, dynamic rehashing runs in amortized time per insertion, preserving the constant-time performance contract.
4. Key Takeaways
#- Direct Addressing vs. Hashing: Direct addressing trades infinite memory for lookups; hashing achieves expected performance in compact memory by mapping keys into .
- Prime Moduli: The division method requires prime table sizes to prevent low-order bitmasking collisions.
- The Birthday Paradox: Collisions occur with probability after only insertions ( keys for ).
- Load Factor Governance: Maintaining load factor guarantees that search, insert, and delete operations execute in expected time.
Academic Attribution & References
#- Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to Algorithms (4th ed.), Chapter 11: Hash Tables. MIT Press.
- Knuth, D. E. (1998). The Art of Computer Programming, Volume 3: Sorting and Searching (2nd ed.), Section 6.4: Hashing. Addison-Wesley.
- Mitzenmacher, M., & Upfal, E. (2017). Probability and Computing: Randomization and Probabilistic Techniques in Algorithms (2nd ed.), Chapter 5: Balls, Bins, and Random Graphs. Cambridge University Press.