Continue statement in Go - Time & Space Complexity
Let's see how the continue statement affects the time a program takes to run.
We want to know if skipping some steps changes how long the code runs as input grows.
Analyze the time complexity of the following code snippet.
for i := 0; i < n; i++ {
if i%2 == 0 {
continue
}
// some constant time work here
}
This code loops from 0 to n-1, but skips the work when i is even using continue.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop running n times.
- How many times: The loop runs n times, but work inside runs about half the times.
Even though some steps are skipped, the loop still checks all n items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop checks, 5 work executions |
| 100 | 100 loop checks, 50 work executions |
| 1000 | 1000 loop checks, 500 work executions |
Pattern observation: The total steps grow linearly with n, skipping work only halves some operations.
Time Complexity: O(n)
This means the time grows directly with the input size, even if some steps are skipped.
[X] Wrong: "Using continue makes the loop run faster and changes time complexity to O(n/2)."
[OK] Correct: Even if some work is skipped, the loop still runs n times, so time still grows linearly with n.
Understanding how continue affects loops helps you explain code efficiency clearly and shows you know how skipping steps impacts performance.
What if we replaced continue with break? How would the time complexity change?