Sobes.tech
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 data structure map is implemented based on a hash table. On average, searching for an element by key in a map has a time complexity of O(1) — constant time. However, in the worst case, such as when there are many collisions, the complexity can degrade to O(n), where n is the number of elements in the map.

Example of using map in Go:

m := make(map[string]int)
m["apple"] = 5
value, ok := m["apple"]
if ok {
    fmt.Println("Value:", value)
}

Thus, for most practical tasks, searching in a map is very fast and efficient.

What is the time complexity of searching for an… - sobes.tech