1. What is a Hash Table?
A hash table (also called hash map) is a data structure that implements an associative array β a collection of key-value pairs. It uses a hash function to compute an index into an array of buckets, where the desired value can be found in O(1) average time.
Think of it like a dictionary: you look up a word (key) and instantly get its definition (value). No need to search through pages!
2. How It Works
Key "apple" βββΊ hash("apple") βββΊ index 3 βββΊ bucket[3] = "red fruit"
βββββββ¬ββββββ¬ββββββ¬ββββββ¬ββββββ¬ββββββ¬ββββββ¬ββββββ
β 0 β 1 β 2 β 3 β 4 β 5 β 6 β 7 β β Array indices
βββββββΌββββββΌββββββΌββββββΌββββββΌββββββΌββββββΌββββββ€
β β β β π β β β β β β Buckets (chains)
β β β βappleβ β β β β
β β β β:red β β β β β
βββββββ΄ββββββ΄ββββββ΄ββββββ΄ββββββ΄ββββββ΄ββββββ΄ββββββ
β
Hash function maps "apple" to index 3index = hash(key) % tableSize3. Collision Handling
A collision occurs when two different keys hash to the same index. There are two main ways to handle this:
Chaining (Used in this tool)
bucket[3]: [appleβred] β [avocadoβgreen]
Each bucket stores a linked list of entries. Search is O(n/m) where n=entries, m=buckets.
Open Addressing
If bucket[3] full, try bucket[4], [5]... Linear probing, quadratic probing, double hashing
Store the entry in the next available slot. Better cache performance.
4. Key Operations
5. Time Complexity
| Operation | Best | Average | Worst |
|---|---|---|---|
| Insert | O(1) | O(1) | O(n) |
| Search | O(1) | O(1) | O(n) |
| Delete | O(1) | O(1) | O(n) |
| Rehash | O(n) | O(n) | O(n) |
Worst case occurs when all keys collide to the same bucket (poor hash function or malicious input).
6. Real-World Applications
7. Knowledge Test
1. What is the average time complexity for searching in a hash table?
2. What happens when two different keys hash to the same index?
3. What triggers a rehash operation?
0 / 3 answered