0
0
Pythonprogramming~5 mins

Counter-based while loop in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Counter-based while loop
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a counter-based while loop changes as the number it counts to gets bigger.

How does the number of steps grow when the loop runs more times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


count = 0
limit = 100
while count < limit:
    print(count)
    count += 1

This code counts from 0 up to one less than the limit, printing each number.

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 up to (limit - 1).
How Execution Grows With Input

Each time the limit gets bigger, the loop runs more times in a straight line.

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

Pattern observation: The number of steps grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the limit gets bigger.

Common Mistake

[X] Wrong: "The loop runs a fixed number of times no matter the limit."

[OK] Correct: The loop actually runs once for each number up to the limit, so bigger limits mean more steps.

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 count down from the limit to zero? How would the time complexity change?"