Lesson 10 of 15
Hash Functions
Hash Functions
A cryptographic hash function maps an arbitrary-length input to a fixed-length output (the digest or hash). Good hash functions satisfy:
- Deterministic — same input always produces same output
- Pre-image resistance — given , hard to find with
- Second pre-image resistance — given , hard to find with same hash
- Collision resistance — hard to find any pair with the same hash
- Avalanche effect — small input change drastically changes output
DJB2 Hash
Invented by Daniel J. Bernstein, DJB2 is a simple non-cryptographic hash widely used in hash tables. Starting with the "magic" seed 5381:
The multiplication by 33 () combined with XOR gives good avalanche properties.
Polynomial Hash
A polynomial rolling hash uses a base and prime modulus :
This is the foundation of Rabin-Karp string matching — a rolling window keeps the polynomial hash updated in per step.
Your Task
Implement:
djb2_hash(s)→ 32-bit unsigned int (use& 0xFFFFFFFFat the end)polynomial_hash(s, base=31, mod=10**9+7)— sum oford(c) * base^ifor each char
Python runtime loading...
Loading...
Click "Run" to execute your code.