Apply function behavior and use cases in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run code using Kotlin's apply function changes as the input grows.
Specifically, how does using apply affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
val list = mutableListOf()
val n = 1000
val result = list.apply {
for (i in 1..n) {
add(i)
}
}
println(result.size)
This code uses apply to add numbers from 1 to n into a list, then prints the list size.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that adds elements to the list. - How many times: Exactly
ntimes, once for each number from 1 to n.
Each time we increase n, the loop runs that many more times, adding one element per run.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the size of n. Double n, double the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the number of items added.
[X] Wrong: "Using apply makes the code run faster because it's a special function."
[OK] Correct: apply just helps organize code; it doesn't change how many times the loop runs or how much work is done.
Understanding how helper functions like apply affect time helps you explain your code clearly and shows you know what really costs time in programs.
"What if we replaced the for loop inside apply with a call to repeat(n)? How would the time complexity change?"