What is Hashing?
The simple concept behind the world's fastest data structures.
The Concept
Hashing is the process of converting a given key (like a word or number) into another value, usually a number, which serves as an index in an array.
Think of a library. Instead of scanning every shelf for a book (Linear Search, O(n)), you look up the book's code in a catalog, which tells you exactly which shelf and slot it is in (Hashing, O(1)).
How It Works
- Key: You have data, e.g., "Alice".
- Hash Function: A math formula converts "Alice" into a number, e.g.,
hash("Alice") = 3. - Hash Table: You store "Alice" at index 3 of your array.
Key: "Alice" ---> [ Hash Function ] ---> Index: 3
[ 0 ] (empty)
[ 1 ] (empty)
[ 2 ] (empty)
[ 3 ] "Alice"
[ 4 ] (empty)
Collisions
What if hash("Bob") also equals 3? This is called a collision.
Two common ways to solve this:
- Chaining: Index 3 doesn't just hold "Alice", it holds a list (Linked List). We add "Bob" to the list at index 3.
- Open Addressing: If index 3 is full, we try index 4, then 5, until we find an empty spot.
Why Use Hashing?
The main advantage is speed.
- Insertion: O(1) - Average case
- Deletion: O(1) - Average case
- Search: O(1) - Average case
This is why Python Dictionaries (`dict`) and Sets (`set`) are so fast.