What is a hash table?
- Algorithms course
- Beginner
- Lesson 69/80
- 4 min
Maps keys to values in O(1) average.
What is a hash table?
A hash table stores key-value pairs and provides O(1) average access time.
A key is converted to an index by a hash function. The value is stored at that index.
Hash function
A hash function converts a key to a fixed-size index. A good hash function reduces collisions.
A common method: index = hash(key) % size. This ensures the index does not exceed the table size.
Practice Hash function
Write hash_func(key, size). Return key % size. Print 1 with print(hash_func(15, 7)).
Starter code
def hash_func(key, size):
# Compute hashSample solution
def hash_func(key, size):
# Compute hash
return key % size
print(hash_func(15, 7))Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the average access complexity of a hash table?
- O(1)
- O(n^2)
- O(log n)
- O(n) Correct answer
Explanation: Average is O(1).
2 Index computation
index = hash(key) % ____
index = hash(key) % size
Explanation: size is right.
3 What is a hash table: match the terms
| Term | Meaning |
|---|---|
Hash table |
Key-value |
Hash function |
Index |
O(1) |
Average |
collision |
Same index |