Adding and updating values in Go - Time & Space Complexity
When we add or update values in a data structure, it is important to know how the time it takes changes as the data grows.
We want to understand how the work needed grows when we add or change values.
Analyze the time complexity of the following code snippet.
package main
func addOrUpdate(m map[string]int, key string, value int) {
m[key] = value
}
This code adds a new key with a value or updates the value if the key already exists in the map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Inserting or updating a key in the map.
- How many times: This operation happens once per call.
Adding or updating a value in a map usually takes about the same time no matter how many items are in the map.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 operation |
| 100 | About 1 operation |
| 1000 | About 1 operation |
Pattern observation: The time to add or update stays roughly the same even as the map grows larger.
Time Complexity: O(1)
This means adding or updating a value takes about the same short time no matter how many items are already stored.
[X] Wrong: "Adding a value takes longer as the map gets bigger because it has to check all keys."
[OK] Correct: Maps use a special way to find keys quickly, so they do not check every key one by one.
Understanding how adding and updating values works helps you explain how data structures keep things fast and efficient in real programs.
"What if we changed the map to a list and added or updated values there? How would the time complexity change?"