Hashing — Definition, Formula & Example
Hashing is a way to store and find data quickly. A hash function turns each key, such as an ID number, into a slot number in a fixed-size table, so you can jump straight to that slot without searching the whole list.
A hash function is a function from a universe of keys to the indices of a hash table. The set is usually far larger than . Two distinct keys with form a collision. The division method uses . Under this method, two keys collide exactly when .
Key Formula
Where:
- = The key being stored, a nonnegative integer
- = The number of slots in the hash table, often chosen to be prime
- = The slot index, the remainder when k is divided by m, between 0 and m − 1
Worked Example
Problem: A hash table has slots, numbered 0 through 6. It uses . Insert the keys 15, 23, 42, and 50 in that order. If a slot is already full, use linear probing: try the next slot, and wrap around after slot 6. Where does each key end up?
Step 1: Compute each key's remainder after dividing by 7. For example, , so 15 hashes to slot 1.
Step 2: Keys 15 and 50 both hash to slot 1, so they collide. The reason is that their difference is a multiple of 7, which means the two keys are congruent mod 7.
Step 3: Key 15 already fills slot 1 and key 23 fills slot 2. Linear probing therefore sends 50 to slot 1 first, then slot 2, then slot 3, which is empty.
Answer: Key 42 goes in slot 0, key 15 in slot 1, key 23 in slot 2, and key 50 in slot 3. Key 50 was moved because it collided with key 15.
Why It Matters
In a data structures course, hash tables are the standard way to get average constant-time lookup. Python dictionaries and Java HashMaps work this way. Cryptographic hash functions such as SHA-256 apply the same idea to file-integrity checks and digital signatures, where finding collisions must be computationally infeasible. Passwords need more than a fast hash: they are stored with salted, deliberately slow hashes such as bcrypt or Argon2.
Common Mistakes
Mistake: Thinking a good hash function never produces collisions.
Correction: When there are more possible keys than slots, the pigeonhole principle guarantees that some distinct keys share a slot. A good hash function spreads keys evenly so collisions are rare, and the table still needs a plan to handle them, such as probing or chaining.
