Loop initialization, condition, update in Java - Time & Space Complexity
We want to understand how the time a loop takes changes as we change its size.
How do the parts of a loop affect how long it runs?
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
System.out.println(i);
}
This loop prints numbers from 0 up to n-1, running once for each number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs the print statement.
- How many times: Exactly n times, once for each number from 0 to n-1.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The work grows directly with n; double n means double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of n.
[X] Wrong: "The loop runs faster because the update step is simple."
[OK] Correct: The update step is very fast, but the loop still runs n times, so the total time depends on how many times it repeats, not just the update.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how to think about efficiency.
"What if we changed the loop to count down from n to 0? How would the time complexity change?"