While–else behavior in Python - Time & Space Complexity
Let's explore how the time it takes to run a while-else loop changes as the input grows.
We want to see how many times the loop runs before it stops or finishes.
Analyze the time complexity of the following code snippet.
count = 0
while count < n:
if count == 5:
break
count += 1
else:
print("Loop finished without break")
This code counts up to n but stops early if count reaches 5. The else runs only if the loop ends normally.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that increases count.
- How many times: min(n, 6) times due to the break at count == 5.
As n grows, the number of loop iterations increases up to 6, then remains constant due to the break.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 (loop runs 3 times, no break) |
| 5 | 5 (loop runs 5 times, no break) |
| 10 | 6 (loop runs 6 times, break when count == 5) |
Pattern observation: The loop runs up to 6 times regardless of n (for large n) due to the early break.
Time Complexity: O(1)
This means the loop runs a constant number of times (at most 6), not growing with n, because it stops early.
[X] Wrong: "The loop always runs n times because it depends on n."
[OK] Correct: The break stops the loop early, so it may run fewer times than n.
Understanding how loops with break and else behave helps you explain code clearly and reason about performance.
"What if we remove the break statement? How would the time complexity change?"