Sobes.tech
Junior — Middle

Can you explain how the HashMap data structure works and how it is implemented in practice?

sobes.tech AI

Answer from AI

HashMap is a data structure that stores key-value pairs and provides fast access to values by key. Its operation is based on using a hash function that transforms the key into an array index (bucket).

Main points:

  • Hash function: calculates the hash code of the key and converts it into an array index.
  • Buckets: an array where elements are stored. Multiple elements can reside in one bucket (collisions).
  • Collisions: when different keys produce the same index. These are usually resolved using a linked list or a tree within the bucket.

When inserting an element into HashMap:

  1. The index is calculated using the hash function.
  2. If the bucket is empty, the element is placed there.
  3. If the bucket is occupied, a search is performed through the list/tree to update the value or add a new node.

When searching:

  1. The index is calculated based on the key.
  2. The element in the bucket is searched by key.

In Python, the equivalent of HashMap is a dictionary (dict), which is implemented using open addressing and dynamic resizing for efficiency.

Example of using a dictionary in Python:

d = {}
d['key'] = 'value'
print(d['key'])  # Outputs 'value'

Thus, HashMap provides an average access time of O(1) with proper implementation and low collision levels.