0
0
Pythonprogramming~5 mins

while True pattern in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: while True pattern
O(n)
Understanding Time 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?

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while True loop runs repeatedly.
  • How many times: It runs until count reaches n, so about n times.
How Execution Grows With Input

As n gets bigger, the loop runs more times, growing in a straight line.

Input Size (n)Approx. Operations
10About 10 loops
100About 100 loops
1000About 1000 loops

Pattern observation: The number of steps grows directly with n.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input n grows.

Common Mistake

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

Interview Connect

Understanding how loops with break conditions work helps you explain how your code runs efficiently in real projects.

Self-Check

"What if we changed the break condition to stop when count reaches n*n? How would the time complexity change?"