0
0
Pythonprogramming~5 mins

While–else behavior in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While-else behavior
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of loop iterations increases up to 6, then remains constant due to the break.

Input Size (n)Approx. Operations
33 (loop runs 3 times, no break)
55 (loop runs 5 times, no break)
106 (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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how loops with break and else behave helps you explain code clearly and reason about performance.

Self-Check

"What if we remove the break statement? How would the time complexity change?"