Math for coding interviews/Hash functions - turning anything into a number
Hash Functions: Turning Anything Into a Number
A hash function takes any input (a string, an object, anything) and converts it into a number. The same input always produces the same number. Think of it as a recipe that takes ingredients and always produces the same dish. The number produced is called the hash.
See it for yourself
An input box on the left. An arrow labeled "hash()" points to a number on the right. Try "apple" → 7823. Try "banana" → 3241. Try "apple" again → 7823 (same every time).
Hash functions - turning anything into a number
A hash function takes any input (a string, an object, anything) and converts it into a number. The same input always produces the same number. Think of it as a recipe that takes ingredients and always produces the same dish. The number produced is called the hash.
Think of it this way: A library catalog number. The title "Moby Dick" always maps to the same shelf location number. Any librarian can compute the location without searching the entire library.
For algorithms: Hash(key) % tableSize tells you exactly which slot to store the value in. This is how O(1) lookup is possible - no searching, just compute the address.
Real-world analogy
A library catalog number. The title "Moby Dick" always maps to the same shelf location number. Any librarian can compute the location without searching the entire library.
Why it matters in interviews
Hash(key) % tableSize tells you exactly which slot to store the value in. This is how O(1) lookup is possible - no searching, just compute the address.