0
0
Javaprogramming~5 mins

Loop execution flow in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Loop execution flow
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n gets bigger, the number of print actions grows the same way.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: The work grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of loop cycles.

Common Mistake

[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.

Interview Connect

Understanding how loops affect time helps you explain code speed clearly and confidently in interviews.

Self-Check

"What if we added a nested loop inside this loop? How would the time complexity change?"