Output using fmt.Println in Go - Time & Space 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.
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 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.
Each time we increase n, we add one more print operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
Pattern observation: The number of operations grows directly with n.
Time Complexity: O(n)
This means the time to print grows in a straight line as we print more items.
[X] Wrong: "Printing 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 and responsiveness.
"What if we printed only every other number instead of all? How would the time complexity change?"