Sub topic 6
Reading Complexity from Loops and Nested Loops
This chapter assumes you can read Python, know what a list is, and have seen the definition of Big O and the rule for dropping constants and lower-order terms. It also assumes you know the common classes from O(1) to O(n!). Here you will use those ideas to derive the complexity of real code by reading its loops.
The method: count how often the innermost work runs
To find the time complexity of a piece of code, follow three steps.
- Choose the input size. Usually this is
n = len(items), or the value of a numeric parameter. - Count how many times the most frequent basic operation runs, as a function of
n. - Simplify the count by dropping constants and lower-order terms.
A basic operation is a step that takes constant time: an arithmetic operation, a comparison, a list index, or an assignment. Loops multiply the cost of their bodies. Statements placed one after another add their costs.
The examples below use three functions.
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)first_item does one index operation whatever the list length, so it is O(1). total runs its loop body once per element, so the cost is about c * n for some constant c, which is O(n). has_duplicate is covered in the nested loop section below.
Sequential statements add
When blocks run one after another, add their costs and keep the largest term.
def summarize(items):
smallest = min(items) # O(n)
largest = max(items) # O(n)
for x in items: # O(n)
if x == smallest or x == largest:
print(x)
for i in range(len(items)): # O(n^2) block
for j in range(len(items)):
if items[i] + items[j] == 0:
print(i, j)The total is n + n + n + n^2, which simplifies to O(n^2). The linear parts are lower-order terms, so the quadratic block dominates.
Note that min(items) and max(items) are loops hidden inside function calls. A library call is not automatically O(1). Always ask what the call does internally.
A single loop
A loop that runs a number of times proportional to n contributes O(n) times the cost of its body.
for x in items:runs n times.for i in range(n):runs n times.for i in range(0, n, 2):runs about n/2 times, which is still O(n), because the constant 1/2 is dropped.for i in range(10):runs 10 times regardless ofn, so it is O(1).
The last case is worth remembering. A loop with a fixed bound does not depend on the input, so it is a constant.
Nested loops
When one loop sits inside another, multiply the iteration counts, provided the inner count does not depend on the outer variable.
def count_pairs(items):
n = len(items)
count = 0
for i in range(n): # n iterations
for j in range(n): # n iterations each time
if items[i] < items[j]:
count += 1
return count # n * n = n^2 comparisons, O(n^2)The loops can have different bounds. If the outer loop runs over a list of length n and the inner loop over a list of length m, the cost is O(n * m). Do not write O(n^2) unless both sizes are really the same quantity. Keep separate variables for separate inputs.
When the inner bound depends on the outer variable
The has_duplicate function above starts the inner loop at i + 1. For i = 0 the inner loop runs n - 1 times, for i = 1 it runs n - 2 times, and so on down to 0 times. The total is
(n - 1) + (n - 2) + ... + 1 + 0 = n(n - 1) / 2Expanding gives n^2/2 - n/2. Drop the lower-order term n/2 and the constant factor 1/2, and the result is O(n^2). Halving the work does not change the complexity class. The code is twice as fast as count_pairs in the limit, but it grows at the same rate.
This sum of consecutive integers appears often. Whenever an inner loop runs i times, or n - i times, for each value of i, expect O(n^2).
def print_triangle(n):
for i in range(n):
for j in range(i): # i iterations, so 0 + 1 + ... + (n-1)
print("*", end="")
print()Here the total work is n(n - 1) / 2 prints, which is O(n^2).
Logarithmic loops
If a loop variable is multiplied or divided by a constant factor each iteration, the number of iterations is logarithmic.
def count_halvings(n):
steps = 0
while n > 1:
n //= 2 # n halves each time
steps += 1
return steps # about log2(n) steps, O(log n)Starting from n = 1024, the values are 1024, 512, 256, ..., 1. That is 10 halvings, and log2(1024) = 10. The same holds for i *= 2 with a condition i < n.
The base of the logarithm does not matter in Big O. Changing the base multiplies the result by a constant, because log_a(n) = log_b(n) / log_b(a). So O(log2 n) and O(log10 n) are the same class, written O(log n).
Binary search is the standard example.
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 iteration discards half of the remaining range, so the loop runs at most about log2(n) + 1 times. The body does a constant amount of work, so the time is O(log n).
Combining a linear loop with a logarithmic loop
def linear_times_log(n):
ops = 0
for i in range(n): # n iterations
j = 1
while j < n: # about log2(n) iterations
j *= 2
ops += 1
return ops # O(n log n)The inner loop does not depend on i, so the counts multiply: O(n log n).
A related case is an inner loop whose bound depends on the outer variable in a doubling pattern. If the outer loop doubles i and the inner loop runs i times, the total is 1 + 2 + 4 + ... + n, which is about 2n. That is O(n), not O(n log n). Do not assume a logarithmic loop always adds a log factor. You must add up the actual counts.
Early exits and data-dependent loops
A loop with return or break may stop before finishing. has_duplicate returns as soon as it finds a match. If the first two items are equal, it makes one comparison. If there are no duplicates, it makes all n(n - 1) / 2.
So one function can have different costs for different inputs of the same size. When you state the complexity, say which case you mean. The usual default is the worst case, which for has_duplicate is O(n^2). The next chapters separate best, worst, and average case in detail.
Loops over a changing structure
Sometimes the loop bound changes as the loop runs.
def drain(items):
while items:
items.pop() # O(1) for the last elementThis runs n times and each pop() from the end is O(1), so the total is O(n). Compare it with this version.
def drain_front(items):
while items:
items.pop(0) # O(n): every remaining element shifts leftHere pop(0) shifts all remaining elements, costing O(n) for a Python list. The loop runs n times, and the cost per iteration is n, n-1, ..., 1, so the total is O(n^2). The loop structure is identical, but the cost of one operation inside it changed the class. This is why you must know the cost of each operation in the body.
Common mistakes
- Counting loops instead of work. Two nested loops are not always O(n^2). Check the bounds and whether either loop is fixed or logarithmic.
- Forgetting hidden loops. Slicing (
items[1:]),inon a list,sum,sorted, string concatenation andlist.insertall cost time proportional to the data they touch. - Merging distinct inputs. Use
nandmwhen there are two sizes. - Treating the value as the size. For
for i in range(k), the cost is O(k) in the valuek. Whether that is "linear" depends on what you call the input size. - Adding a log factor automatically. Check the actual iteration counts, as in the doubling example.
A quick reference
| Code pattern | Iterations | Complexity |
|---|---|---|
| No loop, fixed number of steps | constant | O(1) |
| `for i in range(n)` | n | O(n) |
| Two loops in sequence, each over n | n + n | O(n) |
| Loop inside loop, both over n | n * n | O(n^2) |
| Inner loop from `i + 1` to n | n(n - 1) / 2 | O(n^2) |
| `while n > 1: n //= 2` | log2(n) | O(log n) |
| Linear loop containing a halving loop | n * log2(n) | O(n log n) |
| Loop over n with `pop(0)` inside | n + (n-1) + ... + 1 | O(n^2) |
Putting the analysis together
Use the diagram as a checklist. Ask about each loop in turn, then combine the results with multiplication for nesting and addition for sequence.
Exercises
Exercise
What is the time complexity of this function, and why? def f(n): count = 0 for i in range(n): for j in range(i, n): count += 1 return count
Show answer
O(n^2). The inner loop runs n, n-1, ..., 1 times as i goes from 0 to n-1. The total is n(n + 1) / 2, which is n^2/2 + n/2. Dropping the lower-order term and the constant 1/2 leaves O(n^2).
Exercise
What is the time complexity of this function in terms of n and m? def g(a, b): n, m = len(a), len(b) hits = 0 for x in a: if x in b: hits += 1 return hits where a and b are Python lists.
Show answer
O(n * m). The loop runs n times, and each x in b is a linear search over a list of length m, so the cost is n times m in the worst case. If b were converted to a set first, each membership test would be O(1) on average and the total would be O(n + m).
Exercise
What is the time complexity of this function? def h(n): total = 0 i = 1 while i < n: for j in range(i): total += 1 i *= 2 return total
Show answer
O(n). The inner loop runs i times, and i takes the values 1, 2, 4, ..., up to less than n. The sum is a geometric series that is less than 2n. So the total is O(n), not O(n log n).