Accessing map values in Go - Time & Space Complexity
When we access values in a map, we want to know how long it takes as the map grows.
We ask: How does the time to get a value change when the map has more items?
Analyze the time complexity of the following code snippet.
package main
func getValue(m map[string]int, key string) int {
return m[key]
}
This code returns the value for a given key from a map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct lookup of a key in the map.
- How many times: Exactly once per call.
Looking up a key takes about the same time no matter how many items are in the map.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays roughly the same as the map grows.
Time Complexity: O(1)
This means accessing a value by key takes about the same time no matter how big the map is.
[X] Wrong: "Looking up a key takes longer if the map has more items."
[OK] Correct: Maps use a system that finds keys quickly, so the time does not grow with size.
Understanding how map lookups work helps you explain why your code stays fast even with lots of data.
"What if the map used a list instead of a hash? How would the time complexity change?"