Run function behavior and use cases in Kotlin - Time & Space Complexity
Let's see how the time cost grows when using Kotlin's run function.
We want to know how the number of steps changes as the input or code inside run grows.
Analyze the time complexity of the following code snippet.
val result = run {
var sum = 0
for (i in 1..n) {
sum += i
}
sum
}
println(result)
This code uses run to calculate the sum of numbers from 1 to n.
Look for loops or repeated steps inside the run block.
- Primary operation: The
forloop adding numbers. - How many times: It runs n times, once for each number from 1 to n.
As n grows, the loop runs more times, so the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with n; doubling n doubles the steps.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of n.
[X] Wrong: "The run function itself adds extra loops or slows down the code a lot."
[OK] Correct: The run function just runs the code inside once; it doesn't add loops or repeat work.
Understanding how small helpers like run affect time helps you explain your code clearly and think about efficiency in real projects.
"What if we replaced the for loop inside run with a nested loop running n times inside another loop running n times? How would the time complexity change?"