Map transformation in Kotlin - Time & Space Complexity
When we transform a map, we want to know how the time it takes changes as the map gets bigger.
We ask: How does the work grow when the map has more entries?
Analyze the time complexity of the following code snippet.
val originalMap = mapOf("a" to 1, "b" to 2, "c" to 3)
val transformedMap = originalMap.mapValues { (key, value) -> value * 2 }
println(transformedMap)
This code takes each entry in the map and doubles its value, creating a new map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The mapValues function visits each key-value pair once.
- How many times: Exactly once for each entry in the map.
As the map gets bigger, the work grows in a straight line with the number of entries.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 visits to entries |
| 100 | 100 visits to entries |
| 1000 | 1000 visits to entries |
Pattern observation: Doubling the number of entries doubles the work.
Time Complexity: O(n)
This means the time to transform the map grows directly with the number of entries.
[X] Wrong: "Transforming a map is instant no matter the size."
[OK] Correct: Each entry must be visited once, so bigger maps take more time.
Understanding how map transformations scale helps you write efficient code and explain your choices clearly.
What if we used mapKeys instead of mapValues? How would the time complexity change?