Sub topic 6
Reading complexity from loops and nested loops
This chapter assumes you can write loops and functions in Python and know that Big O drops constants and lower-order terms. Here you will apply those rules to real code.
The working model
To find the time complexity of a loop, count how many times its body runs, then multiply by the cost of one run. Add the costs of code that runs one after another. Multiply the costs of code that sits inside other code. Keep the largest term at the end.
| Code shape | Cost |
|---|---|
| Statement with no loop | O(1) |
| Loop that runs n times with an O(1) body | O(n) |
| Two loops one after the other | O(n) + O(n) = O(n) |
| Loop inside a loop, both running n times | O(n) × O(n) = O(n²) |
| Loop whose variable is halved or doubled each step | O(log n) |
Single and sequential loops
The first three functions below come from the same set of examples. Each shows one shape from the table.
def first_item(items):
return items[0] # O(1): one step regardless of len(items)
def total(items):
s = 0
for x in items: # runs n times
s += x
return s # O(n)
def has_duplicate(items):
n = len(items)
for i in range(n):
for j in range(i + 1, n):
if items[i] == items[j]:
return True
return False # worst case n(n-1)/2 comparisons, which is O(n^2)total runs its body n times. Calling total twice in a row costs n + n = 2n, which simplifies to O(n).
Nested loops that depend on each other
The inner loop in has_duplicate starts at i + 1, so it does not always run n times. For i = 0 it runs n − 1 times, for i = 1 it runs n − 2 times, and so on down to 0. The total is (n − 1) + (n − 2) + … + 0 = n(n − 1)/2, which expands to n²/2 − n/2. Dropping the constant ½ and the lower-order term leaves O(n²).
Do not decide the cost by counting how deeply loops are nested. Count how many times the innermost body runs. Two nested loops usually give O(n²), but a loop nested over a fixed number of iterations, such as for k in range(3), only multiplies the cost by 3.
Loops that halve the range
A loop is logarithmic when the remaining work shrinks by a constant factor on every iteration.
def binary_search(sorted_items, target):
lo, hi = 0, len(sorted_items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sorted_items[mid] == target:
return mid
if sorted_items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Each pass discards half of the range between lo and hi. After k passes about n / 2^k items remain, and the loop stops when that reaches 1. That happens at k ≈ log₂(n), so the loop runs at most about log₂(n) + 1 times and the time is O(log n). A loop written as i *= 2 while i < n has the same cost, because i doubles each step.
Common errors
- Mixing up input sizes. If one loop goes over
aand a nested loop goes overb, the cost is O(a × b), not O(n²). - Ignoring the cost of the body. A loop of n steps that calls
sorted(items)in each step costs O(n × n log n), not O(n). - Forgetting early exits.
has_duplicatecan return after one comparison, so O(n²) describes its worst case, not every run. - Calling every double loop quadratic. Check the bounds of the inner loop first.
Exercise
What is the time complexity of this function, and why? def f(n): count = 0 i = 1 while i < n: for j in range(n): count += 1 i *= 2 return count
Show answer
O(n log n). The while loop doubles i each pass, so it runs about log₂(n) times. Each pass runs the inner for loop n times, so the body runs about n × log₂(n) times.