while True pattern in Python - Time & Space Complexity
We want to understand how long a program using a while True loop runs as the input changes.
Specifically, we ask: how does the number of steps grow when the input size grows?
Analyze the time complexity of the following code snippet.
count = 0
while True:
if count == n:
break
count += 1
This code counts up from zero until it reaches n, then stops.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
while Trueloop runs repeatedly. - How many times: It runs until
countreachesn, so aboutntimes.
As n gets bigger, the loop runs more times, growing in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loops |
| 100 | About 100 loops |
| 1000 | About 1000 loops |
Pattern observation: The number of steps grows directly with n.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input n grows.
[X] Wrong: "Since the loop is while True, it runs forever and time is infinite."
[OK] Correct: The loop has a clear stop condition inside that breaks it when count reaches n. So it does not run forever.
Understanding how loops with break conditions work helps you explain how your code runs efficiently in real projects.
"What if we changed the break condition to stop when count reaches n*n? How would the time complexity change?"