Print and println output in Kotlin - Time & Space Complexity
Let's explore how the time taken by print and println commands changes as we print more items.
We want to know how the program's running time grows when printing more lines.
Analyze the time complexity of the following code snippet.
fun printNumbers(n: Int) {
for (i in 1..n) {
println(i)
}
}
This code prints numbers from 1 up to n, each on its own line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and calls println once per number.
- How many times: Exactly n times, where n is the input size.
As n grows, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
Pattern observation: The work grows directly in step with the number of items printed.
Time Complexity: O(n)
This means the time to print grows in a straight line as you print more lines.
[X] Wrong: "Printing multiple lines happens instantly or in constant time regardless of how many lines."
[OK] Correct: Each print takes time, so more lines mean more total time, growing with the number of lines.
Understanding how simple loops like printing scale helps you explain program speed clearly and confidently.
"What if we used print instead of println inside the loop? How would the time complexity change?"