Output using fmt.Print in Go - Time & Space 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?
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 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.
As n grows, the number of print calls 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 with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to print grows in a straight line as the number of items increases.
[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.
Understanding how output operations scale helps you reason about program speed in real situations.
"What if we used fmt.Println instead of fmt.Print inside the loop? How would the time complexity change?"