Loop execution flow in Java - Time & Space Complexity
Loops run code multiple times, so their speed depends on how many times they repeat.
We want to know how the total work grows as the loop runs more times.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
System.out.println(i);
}
This code prints numbers from 0 up to n-1, running the print statement once each loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the for loop.
- How many times: Exactly n times, once per loop cycle.
As n gets bigger, 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 faster because it just prints simple numbers."
[OK] Correct: Even simple actions inside the loop add up, so the total time still grows with n.
Understanding how loops affect time helps you explain code speed clearly and confidently in interviews.
"What if we added a nested loop inside this loop? How would the time complexity change?"