0
0
Javaprogramming~5 mins

Loop initialization, condition, update in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Loop initialization, condition, update
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As n grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010 print operations
100100 print operations
10001000 print operations

Pattern observation: The work grows directly with n; double n means double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the size of n.

Common Mistake

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

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how to think about efficiency.

Self-Check

"What if we changed the loop to count down from n to 0? How would the time complexity change?"