While loop execution flow in Python - Time & Space 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.
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 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.
Each time n grows, the loop runs more times, directly increasing work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The number of operations grows in a straight line with n.
Time Complexity: O(n)
This means the time taken grows directly in proportion to the input size.
[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.
Understanding how loops grow with input size is a key skill that helps you explain your code clearly and think about efficiency.
"What if we increased count by 2 each time instead of 1? How would the time complexity change?"