Infinite loops in Go - Time & Space Complexity
Infinite loops run without stopping, so their execution time keeps growing forever.
We want to understand what happens to the running time when a loop never ends.
Analyze the time complexity of the following code snippet.
package main
func main() {
for {
// do something simple
}
}
This code runs a loop that never stops, repeating the same action endlessly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The infinite for loop repeating the inner action.
- How many times: Forever, with no end.
Since the loop never stops, the number of operations keeps increasing without limit.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Very large, keeps growing |
| 100 | Even larger, keeps growing |
| 1000 | Much larger, keeps growing |
Pattern observation: The operations grow endlessly, never stopping or slowing down.
Time Complexity: O(∞)
This means the program runs forever, so the time needed is infinite and never finishes.
[X] Wrong: "The loop will finish eventually because computers are fast."
[OK] Correct: An infinite loop has no stopping point, so no matter how fast the computer is, it never ends.
Understanding infinite loops helps you spot when code might run forever, which is important for writing reliable programs.
"What if we add a condition inside the loop to stop after n times? How would the time complexity change?"