Sobes.tech
Junior — Middle

What is the time complexity of searching for an element by key in std::unordered_map?

sobes.tech AI

Answer from AI

The average time complexity of searching for an element by key in std::unordered_map is O(1) — constant time, due to the use of a hash table.

However, in the worst case (for example, with many collisions), the complexity can degrade to O(n), where n is the number of elements in the container.

Example usage:

#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> map;
    map["key"] = 42;
    auto it = map.find("key");
    if (it != map.end()) {
        // Access to the element in average O(1)
        int value = it->second;
    }
}