Sub topic 7
Triangular Loops and Dependent Bounds
This chapter assumes you already know two things from earlier chapters. First, independent nested loops multiply: an outer loop of n iterations around an inner loop of m iterations costs n * m steps. Second, the arithmetic series 0 + 1 + 2 + ... + (n - 1) equals n(n - 1)/2. Here you will combine them to count nested loops where the inner loop's bounds change with the outer variable.
Why Multiplication Breaks
Multiplication works when every pass of the outer loop runs the inner loop the same number of times. Many real algorithms do not behave that way. Comparing every pair of items, selection sort, bubble sort, and building a triangular table all use an inner loop that starts or stops at the outer variable i. That makes the inner count a function of i.
When the inner count changes from one outer iteration to the next, "outer count times inner count" is no longer a defined quantity. The method that always works is to sum the inner count over every value of the outer variable:
- Write down how many times the inner loop runs for one fixed value of
i. Call itf(i). - Add
f(i)over every valueitakes. - Simplify the sum with a known series formula.
Independent nesting is the special case where f(i) is the constant m. Then the sum of m taken n times is n * m.
The Canonical Triangle: All Pairs
This loop visits every unordered pair (i, j) with i < j:
def count_pairs(n):
steps = 0
for i in range(n):
for j in range(i + 1, n):
steps += 1
return steps
for n in (5, 10, 100):
assert count_pairs(n) == n * (n - 1) // 2
print(count_pairs(10)) # 45Apply the method.
- For a fixed
i, the inner loop isrange(i + 1, n). From the bounds rule, it runsn - (i + 1) = n - 1 - itimes. - The outer variable takes the values
i = 0, 1, ..., n - 1, so the inner counts aren - 1, n - 2, ..., 1, 0. - That is the arithmetic series
0 + 1 + ... + (n - 1)in reverse order, which equalsn(n - 1)/2.
For n = 10, the total is 10 * 9 / 2 = 45, which matches the program's output.
The chart below shows the inner counts for n = 6. The bars shrink by one each time, and their total area (5 + 4 + 3 + 2 + 1 + 0 = 15) is the step count.
The name "triangular" comes from geometry. Picture an n by n grid of (i, j) cells. The loop covers only the cells strictly above the diagonal, which is a bit less than half the square. Half of n^2, minus the n diagonal cells shared out, gives (n^2 - n)/2.
Off-by-One Variants
Small changes to the inner bounds shift the total by about n. They don't change the order of growth, but they do change the exact count. If you are checking a prediction with a counter, you need the exact count.
| Inner loop | f(i) | Values summed | Total |
|---|---|---|---|
| `range(i + 1, n)` | `n - 1 - i` | n-1, ..., 0 | `n(n - 1)/2` |
| `range(i)` | `i` | 0, ..., n-1 | `n(n - 1)/2` |
| `range(i + 1)` | `i + 1` | 1, ..., n | `n(n + 1)/2` |
| `range(i, n)` | `n - i` | n, ..., 1 | `n(n + 1)/2` |
| `range(n - 1 - i)` | `n - 1 - i` | n-1, ..., 0 | `n(n - 1)/2` |
The last row is the inner loop of bubble sort. After each pass, the largest remaining element is in its final place, so the next pass can stop one position earlier.
def bubble_sort_comparisons(items):
a = list(items)
n = len(a)
comparisons = 0
for i in range(n - 1):
for j in range(n - 1 - i):
comparisons += 1
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
return a, comparisons
result, c = bubble_sort_comparisons([5, 2, 9, 1, 7, 3])
print(result, c) # [1, 2, 3, 5, 7, 9] 15
assert c == 6 * 5 // 2Here the outer loop runs only n - 1 times, for i = 0, ..., n - 2. The inner counts are n - 1, n - 2, ..., 1, so the total is still n(n - 1)/2. When i = n - 1, the inner count would have been 0, so dropping that last outer pass removes no comparisons.
Deeper Triangles: Three Dependent Levels
The same idea extends to more levels. This loop visits every triple i < j < k:
from math import comb
def count_triples(n):
steps = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
steps += 1
return steps
for n in (3, 10, 30):
assert count_triples(n) == comb(n, 3) == n * (n - 1) * (n - 2) // 6
print(count_triples(10)) # 120You can sum level by level, but there is a shortcut. Each iteration of the innermost body corresponds to exactly one way of choosing 3 distinct indices from n, listed in increasing order. So the count is the binomial coefficient C(n, 3) = n(n - 1)(n - 2)/6. In general, d loops nested with strictly increasing indices run C(n, d) times, which is about n^d / d!. For a fixed d, that is Theta(n^d). The 1/d! factor makes it much smaller than the n^d you would get from d independent loops.
When f(i) Is Not Linear
The inner count does not have to change by one each time. Its shape decides which series you need, and the series decides the order of growth.
Quadratic Inner Bound
def count_square_inner(n):
steps = 0
for i in range(n):
for j in range(i * i):
steps += 1
return steps
n = 10
assert count_square_inner(n) == (n - 1) * n * (2 * n - 1) // 6
print(count_square_inner(n)) # 285Here f(i) = i^2, and the sum of squares 0^2 + ... + (n - 1)^2 = (n - 1)n(2n - 1)/6, which is about n^3/3. Two loops nested in the code give cubic growth here. You cannot read the order of growth from how deep the loops are nested. You have to sum.
Dependent Step Size: a Harmonic Sum
The outer variable can also control the inner loop's step size:
import math
def count_strided(n):
steps = 0
for i in range(1, n + 1):
for j in range(0, n, i):
steps += 1
return steps
n = 10
assert count_strided(n) == sum(math.ceil(n / i) for i in range(1, n + 1))
print(count_strided(n)) # 33For a fixed i, range(0, n, i) runs ceil(n / i) times. The total is about n/1 + n/2 + ... + n/n = n * H_n, where H_n is the harmonic number. H_n grows like ln n, so the loop is Theta(n log n). Patterns like this show up in sieve algorithms and in loops over the divisors of every number up to n.
| f(i) | Series | Order of growth |
|---|---|---|
| constant `m` | `n * m` | `Theta(n m)` |
| `i` or `n - i` | arithmetic | `Theta(n^2)` |
| `i^2` | sum of squares | `Theta(n^3)` |
| `n / i` | harmonic | `Theta(n log n)` |
Bounding Without an Exact Formula
Sometimes the sum has no neat closed form, or you only need the order of growth. Then you can squeeze it between two simple bounds.
- Upper bound: every inner count is at most its largest value. For
count_pairs,f(i) <= n, so the total is at mostn * n = n^2. - Lower bound: drop the smaller half of the terms. For
i < n/2,f(i) = n - 1 - i >= n/2 - 1. There aren/2such values ofi, so the total is at least(n/2)(n/2 - 1), which is roughlyn^2/4.
Both bounds are a constant times n^2, so the count is Theta(n^2). You get this without ever writing n(n - 1)/2. The trick works whenever f(i) is monotone: half the terms are at least half the largest term.
Common Errors
- Treating the shrinking inner loop as "O(n) on average, so O(n) total." The inner loop averages about
n/2iterations, and it runsntimes. The average multiplies the outer count. It does not replace it. - Multiplying the maximum inner count by the outer count and calling it exact.
n * (n - 1)is twice the true count forcount_pairs. It is a valid upper bound but the wrong number. - Forgetting empty inner loops. When
f(i) = 0, the outer loop still runs its own header and any code outside the inner loop. If the outer body does constant workcas well, the total isn(n - 1)/2 + c * n. That is stillTheta(n^2), but the exact count is different. - Reading the order of growth from nesting depth. The
i * iandn / iexamples show that two nested loops can be cubic orn log n.
Exercises
Exercise
How many times does the body run, exactly, as a function of n? for i in range(n): for j in range(i, n): body()
Show answer
For a fixed i, range(i, n) runs n - i times. Summing over i = 0, ..., n - 1 gives n + (n - 1) + ... + 1 = n(n + 1)/2. For n = 4 that is 10. The loop is Theta(n^2).
Exercise
Count the body executions of for i in range(1, n + 1): for j in range(0, i, 2): body() for n = 6, and give the order of growth.
Show answer
For a fixed i, range(0, i, 2) runs ceil(i / 2) times. For i = 1..6 the counts are 1, 1, 2, 2, 3, 3, so the total is 12. In general the sum is about n^2/4, which is Theta(n^2). Halving the inner step halves the constant but leaves the growth rate unchanged.
Exercise
A function has four nested loops with strictly increasing indices i < j < k < l, all below n. What is the exact count for n = 8, and how does it compare with four independent loops of n iterations each?
Show answer
The count is C(8, 4) = 70. Four independent loops would run 8^4 = 4096 times. Both are Theta(n^4), but the dependent version is smaller by roughly a factor of 4! = 24, plus lower-order terms.
Exercise
Show that for i in range(n): for j in range(n - i): body() is Theta(n^2) using only upper and lower bounds, without a series formula.
Show answer
Upper bound: n - i <= n for every i, so the total is at most n^2. Lower bound: for i < n/2, n - i > n/2, and there are n/2 such values of i, so the total is at least n^2/4. Both bounds are constant multiples of n^2, so the count is Theta(n^2).