Sub topic 4
Analyzing Loops and Nested Loops
This chapter assumes you can read loops in Python or C, know that O, Omega, and Theta describe growth rates, and can sum simple series such as 1 + 2 + ... + n and geometric series.
The working model
To find the running time of a loop, count how many times its basic operation runs, then express the count as a function of the input size n. The basic operation is the statement executed most often, such as a comparison or an assignment. Work that runs once, such as initialization, only adds a constant.
Two questions decide the count:
- How does the loop variable change each iteration? Adding a constant gives a linear count. Multiplying or dividing by a constant gives a logarithmic count. Squaring gives a log log count.
- Does an inner loop's bound depend on an outer loop's variable? If not, multiply the counts. If it does, sum the inner counts over every value of the outer variable.
Single loops
The table gives the exact iteration count for each common shape, assuming n is at least 2.
| Loop | Iterations | Class |
|---|---|---|
| `for i in range(n)` | n | Theta(n) |
| `i = 1; while i < n: i *= 2` | ceil(log2 n) | Theta(log n) |
| `i = n; while i > 1: i //= 2` | floor(log2 n) | Theta(log n) |
| `i = 2; while i < n: i = i * i` | about log2 log2 n | Theta(log log n) |
| `i = 1; while i * i <= n: i += 1` | floor(sqrt n) | Theta(sqrt n) |
The base of the logarithm does not matter inside Theta. Multiplying by 3 instead of 2 changes the count only by a constant factor.
Nested loops
Independent bounds: multiply
If the inner loop runs a fixed number of times for every outer iteration, multiply the two counts. An outer loop of n iterations around an inner loop that doubles j up to n runs n times log n, so it is Theta(n log n).
Dependent bounds: sum a series
If the inner count depends on the outer variable, add up the inner counts. Take for i in range(n): for j in range(i). The inner loop runs 0, 1, 2, ..., n-1 times, so the total is n(n-1)/2, which is Theta(n^2).
A geometric series behaves differently. Consider an outer loop where i doubles from 1 up to n, and an inner loop that runs i times. The total is 1 + 2 + 4 + ... + 2^k, where 2^k is at most n. That sum is less than 2n, so the loop is Theta(n), not Theta(n log n). The last term dominates, and a naive "outer count times inner maximum" gives log n times n, which is too large.
Harmonic sums
Take for i in 1..n: for j = i; j <= n; j += i. For a given i, the inner loop runs about n/i times. The total is n(1 + 1/2 + ... + 1/n), which is about n ln n, so it is Theta(n log n). This pattern appears in the sieve of Eratosthenes.
Verifying counts by running them
The script below counts the basic operations directly. You can compare each count with the formula you derived.
def halving(n):
c, i = 0, 1
while i < n:
i *= 2
c += 1
return c
def triangular(n):
c = 0
for i in range(n):
for j in range(i):
c += 1
return c
def doubling_outer(n):
c, i = 0, 1
while i <= n:
for j in range(i):
c += 1
i *= 2
return c
def log_inner(n):
c = 0
for i in range(n):
j = 1
while j < n:
j *= 2
c += 1
return c
def squaring(n):
c, i = 0, 2
while i < n:
i = i * i
c += 1
return c
def harmonic(n):
c = 0
for i in range(1, n + 1):
for j in range(i, n + 1, i):
c += 1
return c
n = 1000
print("halving", halving(n))
print("triangular", triangular(n // 10))
print("doubling_outer", doubling_outer(n))
print("log_inner", log_inner(n))
print("squaring", squaring(n))
print("harmonic", harmonic(n))With these inputs, halving prints 10 and triangular(100) prints 4950, which is 100 * 99 / 2. doubling_outer prints 1023, which is below 2n. log_inner prints 10000, which is n times 10. squaring prints 4. The harmonic count is close to n ln n.
Common errors
- Multiplying worst-case bounds blindly. The doubling-outer loop is Theta(n), not Theta(n log n), because most inner loops are short.
- Treating
i += 2ori *= 3as different classes. Constant factors and log bases vanish inside Theta. - Ignoring work inside the loop body. If the body calls a function that costs O(n), such as slicing a list or calling
lenon a linked structure, multiply it in. - Mixing up the loop variable's start. A loop that starts at
i = 0and doesi *= 2never terminates. Check that the variable moves toward the exit condition. - Forgetting the exit condition when it is not on n.
while i * i <= nis Theta(sqrt n), not Theta(n). - Counting only the outer loop when two sequential loops run one after another. Sequential loops add, so the larger term wins. Nested loops multiply.
Exercises
Exercise
What is the tight bound for this code? i = n while i >= 1: for j in range(i): work() i = i // 2
Show answer
The inner loop runs n, n/2, n/4, ..., 1 times. This geometric series sums to less than 2n, so the code is Theta(n).
Exercise
What is the tight bound for this code, and why is it not Theta(n log n)? i = 1 while i <= n: j = n while j > 1: j = j // 2 i = i * 2
Show answer
The outer loop runs about log2 n times. The inner loop runs about log2 n times for each outer iteration, and its bound does not depend on i. The total is Theta(log n) times Theta(log n), which is Theta(log^2 n). The code does not touch n linearly anywhere, so no factor of n appears.