0
0
Goprogramming~5 mins

Output using fmt.Println in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Output using fmt.Println
O(n)
Understanding Time Complexity

Let's see how the time it takes to print output grows as we print more items.

We want to know how the number of print statements affects the total time.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

package main

import "fmt"

func main() {
    var n int = 10
    for i := 0; i < n; i++ {
        fmt.Println(i)
    }
}

This code prints numbers from 0 up to n-1, one per line.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop runs and calls fmt.Println once each time.
  • How many times: Exactly n times, where n is the input size.
How Execution Grows With Input

Each time we increase n, we add one more print operation.

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

Pattern observation: The number of operations grows directly with n.

Final Time Complexity

Time Complexity: O(n)

This means the time to print grows in a straight line as we print more items.

Common Mistake

[X] Wrong: "Printing is instant and does not affect time complexity."

[OK] Correct: Each print takes time, so more prints mean more total time.

Interview Connect

Understanding how output operations scale helps you reason about program speed and responsiveness.

Self-Check

"What if we printed only every other number instead of all? How would the time complexity change?"