DSA — Hash Tables
What is a Hash Table?
A data structure that maps keys to values using a hash function.
class HashTable:
def __init__(self, size=10):
self.size = size
self.table = [[] for _ in range(size)]
def hash_function(self, key):
return hash(key) % self.size
def insert(self, key, value):
index = self.hash_function(key)
for pair in self.table[index]:
if pair[0] == key:
pair[1] = value
return
self.table[index].append([key, value])
def get(self, key):
index = self.hash_function(key)
for pair in self.table[index]:
if pair[0] == key:
return pair[1]
return None
def delete(self, key):
index = self.hash_function(key)
for i, pair in enumerate(self.table[index]):
if pair[0] == key:
del self.table[index][i]
return True
return False
Operations
| Operation | Average | Worst Case |
|---|---|---|
| Insert | O(1) | O(n) |
| Search | O(1) | O(n) |
| Delete | O(1) | O(n) |
Collision Handling
| Method | Description |
|---|---|
| Chaining | Linked lists at each slot |
| Open Addressing | Find next empty slot |
Mini Practice
- Implement a hash table
- Handle collisions
- Use hash table for counting
- Implement a cache
Up Next
Continue with HashMap — HashMap implementation.
Related Topics
Frequently Asked Questions about Hash Tables
What is Hash Tables in DSA?
Hash Tables is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Hash Tables?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Hash Tables.
Why is Hash Tables important in DSA?
Hash Tables is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.