Function declaration syntax in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run a function changes as the input changes.
Specifically, we ask: how does the function's work grow when input size grows?
Analyze the time complexity of the following code snippet.
fun printNumbers(n: Int) {
for (i in 1..n) {
println(i)
}
}
This function prints numbers from 1 up to n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each number.
- How many times: It runs exactly n times, once for each number.
As n grows, 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 n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the input size.
[X] Wrong: "The function runs in constant time because it just prints numbers."
[OK] Correct: Printing happens once for each number, so more numbers mean more work.
Understanding how loops affect time helps you explain your code clearly and shows you know how programs grow with input.
"What if we changed the function to print only even numbers up to n? How would the time complexity change?"