0
0
Goprogramming~5 mins

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

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

We want to understand how long it takes to run code that prints output using fmt.Print.

Specifically, how does the time change when we print more items?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

package main

import "fmt"

func main() {
    n := 1000
    for i := 0; i < n; i++ {
        fmt.Print(i, " ")
    }
}

This code prints numbers from 0 up to n-1 on the same line.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop runs and calls fmt.Print 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 calls grows the same way.

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

Pattern observation: The work grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to print grows in a straight line as the number of items increases.

Common Mistake

[X] Wrong: "Printing output 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 in real situations.

Self-Check

"What if we used fmt.Println instead of fmt.Print inside the loop? How would the time complexity change?"