0
0
PHPprogramming~5 mins

While loop execution model in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While loop execution model
O(n)
Understanding Time Complexity

We want to understand how the time a while loop takes changes as the input grows.

How many times does the loop run when the input gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$count = 0;
while ($count < $n) {
    echo $count . "\n";
    $count++;
}
    

This code prints numbers from 0 up to one less than n using a while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs repeatedly.
  • How many times: It runs once for each number from 0 to n-1, so n times.
How Execution Grows With Input

As n grows, the loop runs more times, directly matching n.

Input Size (n)Approx. Operations
10About 10 times
100About 100 times
1000About 1000 times

Pattern observation: The number of operations grows evenly as n grows.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line with the size of n.

Common Mistake

[X] Wrong: "The while loop runs only once no matter the input size."

[OK] Correct: The loop runs as many times as the condition allows, so it depends on n, not just once.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.

Self-Check

"What if we changed the loop to increase count by 2 each time? How would the time complexity change?"