For loop over collections in Kotlin - Time & Space Complexity
When we use a for loop to go through a collection, we want to know how the time it takes changes as the collection grows.
We ask: How does the work increase when the list gets bigger?
Analyze the time complexity of the following code snippet.
fun printAllNames(names: List) {
for (name in names) {
println(name)
}
}
This code goes through each name in the list and prints it out one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for loop that visits each item in the list.
- How many times: Exactly once for each item in the list.
As the list gets bigger, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the list.
[X] Wrong: "The loop runs faster because it just prints simple text."
[OK] Correct: The speed depends on how many times the loop runs, not what it does inside. Even simple actions add up when repeated many times.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.
"What if we nested another for loop inside this one to print pairs of names? How would the time complexity change?"