Junior — Middle
What is the time complexity of searching for an element by key in a map data structure?
sobes.tech AI
Answer from AI
In Go, the map data structure is implemented as a hash table. The average time complexity for searching an element by key is O(1).
This means access to an element by key is very fast, regardless of the size of the map.
However, in the worst case (e.g., many hash collisions), the complexity can degrade to O(n), where n is the number of elements, but such situations are rare with good hashing.
Example of using a map in Go:
m := make(map[string]int)
m["key"] = 42
value, ok := m["key"]
if ok {
fmt.Println("Value:", value)
}