For loop with index (withIndex) in Kotlin - Time & Space Complexity
We want to understand how the time needed to run a for loop with index changes as the list size grows.
How does the number of steps grow when we loop over more items?
Analyze the time complexity of the following code snippet.
val items = listOf("apple", "banana", "cherry")
for ((index, item) in items.withIndex()) {
println("Item #$index is $item")
}
This code loops through a list of items, printing each item with its position number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once for each item in the list.
As the list gets bigger, the number of steps grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The steps increase evenly as the list size increases.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "Using withIndex makes the loop slower because it adds extra work."
[OK] Correct: The withIndex function just pairs each item with its index without extra loops, so it still goes through the list only once.
Knowing how loops with indexes scale helps you explain your code clearly and shows you understand how programs handle data efficiently.
"What if we nested another loop inside this one that also goes through the list? How would the time complexity change?"