Counter-based while loop in Python - Time & Space 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?
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 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).
Each time the limit gets bigger, the loop runs more times in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times |
| 100 | About 100 times |
| 1000 | About 1000 times |
Pattern observation: The number of steps grows directly with the input size.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the limit gets bigger.
[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.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.
"What if we changed the loop to count down from the limit to zero? How would the time complexity change?"