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 time complexity of searching for an element by key in std::unordered_map in the average case is O(1), which is constant time. This is achieved by using a hash table, where keys are hashed and elements are distributed across buckets.
However, in the worst case, when many collisions occur (for example, all keys hash to the same bucket), the complexity can degrade to O(n), where n is the number of elements.
Example usage:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> map = {{1, "one"}, {2, "two"}, {3, "three"}};
auto it = map.find(2);
if (it != map.end()) {
std::cout << "Found: " << it->second << std::endl;
}
return 0;
}