Sobes.tech
Junior

What is the time complexity of the algorithm for retrieving an element from a Map data structure?

sobes.tech AI

Answer from AI

In the average case — $O(1)$.

In the worst case (with a large number of collisions) — $O(n)$, where $n$ is the number of elements in the Map.

This is because the Map uses a hash table. The access time to an element depends on the quality of the hash function and the collision resolution implementation. Ideally, each element has a unique hash and instant access. In case of collisions, it may be necessary to iterate over elements with the same hash.

// Example of accessing an element in a Map:
const myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');

const value = myMap.get('key1'); // In the average case - O(1)