Destructuring in collection iteration in Kotlin - Time & Space Complexity
When we use destructuring to loop over collections, we want to know how the time needed grows as the collection gets bigger.
We ask: How does the number of steps change when the list has more items?
Analyze the time complexity of the following code snippet.
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
for ((key, value) in map) {
println("Key: $key, Value: $value")
}
This code loops over a map and uses destructuring to get each key and value pair.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each entry in the map.
- How many times: Once for every key-value pair in the map.
Each item in the map is visited once, so the work grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of steps grows in a straight line with the number of items.
Time Complexity: O(n)
This means the time to finish grows directly with how many items are in the collection.
[X] Wrong: "Destructuring makes the loop slower because it adds extra steps."
[OK] Correct: Destructuring just unpacks each item during the loop, which is done once per item and does not add extra loops or nested work.
Understanding how loops with destructuring scale helps you explain your code clearly and shows you know how to reason about performance in real tasks.
"What if we nested another loop inside that also uses destructuring? How would the time complexity change?"