0
0
Pythonprogramming~5 mins

While loop execution flow in Python - Time & Space Complexity

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

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

Specifically, how many times the loop runs affects the total work done.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


count = 0
while count < n:
    print(count)
    count += 1

This code prints numbers from 0 up to n-1 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

Each time n grows, the loop runs more times, directly increasing work.

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

Pattern observation: The number of operations grows in a straight line with n.

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows directly in proportion to the input size.

Common Mistake

[X] Wrong: "The while loop runs forever or a fixed number of times regardless of n."

[OK] Correct: The loop stops when count reaches n, so it depends exactly on n, not fixed or infinite.

Interview Connect

Understanding how loops grow with input size is a key skill that helps you explain your code clearly and think about efficiency.

Self-Check

"What if we increased count by 2 each time instead of 1? How would the time complexity change?"