0
0
Kotlinprogramming~5 mins

Print and println output in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Print and println output
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of print actions grows the same way.

Input Size (n)Approx. Operations
1010 print calls
100100 print calls
10001000 print calls

Pattern observation: The work grows directly in step with the number of items printed.

Final Time Complexity

Time Complexity: O(n)

This means the time to print grows in a straight line as you print more lines.

Common Mistake

[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.

Interview Connect

Understanding how simple loops like printing scale helps you explain program speed clearly and confidently.

Self-Check

"What if we used print instead of println inside the loop? How would the time complexity change?"