Welcome to the exciting world of Hashing! This lesson will guide you through understanding and implementing Hashing, a fundamental concept in Computer Science.
<a name="introduction"></a>
Hashing is a technique used for efficient data storage and retrieval. The main idea is to map keys to values using a hash function. This process allows for fast lookup times and makes working with large datasets more manageable.
<a name="why-use-hashing"></a>
Hashing offers several advantages over traditional data structures:
<a name="types-of-hashing"></a>
There are several types of hashing, but we'll focus on two primary ones:
<a name="creating-a-hash-function"></a>
A good hash function should:
<a name="collision-resolution"></a>
Collisions occur when two or more keys map to the same index. To handle collisions, we use several methods, including:
<a name="simple-hash-table-implementation"></a>
Let's create a simple hash table using a Python dictionary for chaining and linear probing for open addressing.
# Simple Hash Table with Chaining (using Python Dictionary)
def create_hash_table():
hash_table = {}
return hash_table
def hash_function(key, size):
return hash(key) % size
def put(hash_table, key, value, size):
index = hash_function(key, size)
if index in hash_table:
hash_table[index].append((key, value))
else:
hash_table[index] = [(key, value)]
def get(hash_table, key, size):
index = hash_function(key, size)
if index in hash_table:
for k, v in hash_table[index]:
if k == key:
return v
return None
# Example usage
hash_table = create_hash_table()
put(hash_table, 'apple', 123, 10)
put(hash_table, 'banana', 456, 10)
print(get(hash_table, 'apple', 10)) # Output: 123
# Simple Hash Table with Linear Probing
def create_hash_table_linear_probing(size):
hash_table = [None] * size
return hash_table
def hash_function(key, size):
return hash(key) % size
def put(hash_table, key, value, size):
index = hash_function(key, size)
while hash_table[index] is not None:
index = (index + 1) % size
hash_table[index] = (key, value)
def get(hash_table, key, size):
index = hash_function(key, size)
while hash_table[index] is not None and hash_table[index][0] != key:
index = (index + 1) % size
return hash_table[index][1] if hash_table[index] else None
# Example usage
hash_table = create_hash_table_linear_probing(10)
put(hash_table, 'apple', 123, 10)
put(hash_table, 'banana', 456, 10)
print(get(hash_table, 'apple', 10)) # Output: 123
<a name="quiz"></a>
What is the time complexity for accessing values in a well-designed hash table?
That's all for our Hashing introduction lesson! Keep exploring and practicing to master this essential concept. Happy coding! šš