Loop execution flow in Go - Time & Space Complexity
Loops are a common way to repeat actions in code. Understanding how many times a loop runs helps us see how the program's work grows.
We want to know: how does the time to finish change when the loop runs more times?
Analyze the time complexity of the following code snippet.
for i := 0; i < n; i++ {
fmt.Println(i)
}
This code prints numbers from 0 up to n-1, repeating the print action n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the loop.
- How many times: Exactly n times, once for each loop cycle.
As n grows, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of loop cycles.
[X] Wrong: "The loop runs instantly no matter how big n is."
[OK] Correct: Each loop cycle takes time, so more cycles mean more total time.
Knowing how loops affect time helps you explain your code clearly and shows you understand how programs grow with input size.
"What if we added a nested loop inside this loop? How would the time complexity change?"