Data Structures & Algorithms / Module 2: Hashing
Topic 2.1
Hash functions
Turning data into a number that is consistent and evenly spread, and why letter order has to count.
Watch: every letter becomes a number, then those numbers combine into one drawer number. The same word always lands in the same drawer.
- moving now
- being checked
- no longer used
Like a fingerprint
The same person always has the same fingerprint, and two different people almost certainly have different ones. A hash function gives every piece of data a "fingerprint" in the form of a number. A hash map uses that number to pick a drawer, and many other systems use it to recognise data quickly.
Why order matters
The simplest method is to add up every letter's code. The trouble: listen and silent contain the same letters, so their sums are equal and they always land in the same drawer. Every set of words with the same letters collides.
The fix: before adding the next letter, multiply the running total by a number (often 31). Now a letter's position matters. Try both in the figure. Java uses exactly this for String.hashCode().
Code, for programmersTwo simple hash functions
const sumHash = (s) => [...s].reduce((h, c) => h + c.charCodeAt(0), 0);
const polyHash = (s) => [...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) | 0, 0);
sumHash("listen") === sumHash("silent"); // true: a collision
polyHash("listen") === polyHash("silent"); // falseWhat makes a good hash function
- Consistent: same input, same number. Otherwise stored data can never be found again.
- Spread out: similar inputs (say user1 and user2) give very different numbers, so the drawers fill evenly.
- Fast: it runs on every store and every lookup, so it can't be slow.
Quiz
What is the one rule a hash function must follow?
Why is adding up letter codes a poor hash function?
To store users' passwords you should use…
0 of 3 answered.