For loop as while in Go - Time & Space Complexity
We want to see how the time it takes to run a for loop used like a while loop changes as the input grows.
How does the number of steps grow when the loop runs more times?
Analyze the time complexity of the following code snippet.
package main
func countDown(n int) {
for n > 0 {
n--
}
}
This code counts down from n to zero using a for loop that acts like a while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and decreases n by 1 each time.
- How many times: The loop runs exactly n times until n reaches zero.
Each time n gets bigger, the loop runs more times, directly matching n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of steps grows in a straight line with n.
Time Complexity: O(n)
This means the time to finish grows directly with the size of n.
[X] Wrong: "The loop runs a fixed number of times no matter what n is."
[OK] Correct: The loop depends on n and runs once for each count down, so bigger n means more steps.
Understanding how loops grow with input helps you explain your code clearly and shows you know how programs scale.
"What if we changed the loop to decrease n by 2 each time? How would the time complexity change?"