A Hash Map (also known as a hash table) is a data structure used to store key-value pairs efficiently, providing average constant time complexity (O(1)) for search, insert, and delete operations. Here are the fundamental concepts and workings of a hash map:
Collisions occur when two different keys generate the same hash value and thus the same bucket. There are several methods to handle collisions:
Here is a simple example of a hash map implementation in Python:
class HashMap:
def __init__(self, size=10):
self.size = size
self.map = [[] for _ in range(size)]
def _get_hash(self, key):
return hash(key) % self.size
def add(self, key, value):
key_hash = self._get_hash(key)
key_value = [key, value]
for pair in self.map[key_hash]:
if pair[0] == key:
pair[1] = value
return True
self.map[key_hash].append(key_value)
return True
def get(self, key):
key_hash = self._get_hash(key)
for pair in self.map[key_hash]:
if pair[0] == key:
return pair[1]
return None
def delete(self, key):
key_hash = self._get_hash(key)
for pair in self.map[key_hash]:
if pair[0] == key:
self.map[key_hash].remove(pair)
return True
return False
# Example usage
h = HashMap()
h.add("key1", "value1")
h.add("key2", "value2")
print(h.get("key1")) # Output: value1
h.delete("key1")
print(h.get("key1")) # Output: None
In summary, a hash map is an extremely efficient and versatile data structure, especially suitable for scenarios requiring fast data access times.