Repeat function for simple repetition in Kotlin - Time & Space Complexity
We want to understand how the time taken by Kotlin's repeat function changes as we repeat an action more times.
The question is: How does the number of repetitions affect the total work done?
Analyze the time complexity of the following code snippet.
fun printHello(times: Int) {
repeat(times) {
println("Hello")
}
}
printHello(5)
This code prints "Hello" a number of times given by times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
repeatfunction runs the print statement multiple times. - How many times: Exactly
timestimes, as given by the input.
Each time we increase times, the print action happens that many more times.
| Input Size (times) | Approx. Operations (prints) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means if you double the number of repetitions, the total work roughly doubles too.
[X] Wrong: "The repeat function runs instantly no matter how many times."
[OK] Correct: Each repetition runs the code inside once, so more repetitions mean more work and more time.
Understanding how simple loops like repeat scale helps you explain how programs handle repeated tasks efficiently.
"What if we nested one repeat inside another? How would the time complexity change?"