Sub topic 7
Triangular Loops and Dependent Bounds
This chapter assumes you can read Python for loops, count the iterations of a single range, multiply the costs of independent nested loops, and use the arithmetic series formula 1 + 2 + ... + k = k(k+1)/2 from the previous chapter.
When the Inner Loop Depends on the Outer Variable
In an independent nested loop, the inner loop runs the same number of times on every pass of the outer loop, so you multiply. When the inner loop's bounds use the outer variable, each pass of the outer loop does a different amount of work. You cannot multiply. You add up the inner count for each outer value instead.
Here is the standard example. It visits every unordered pair of indices exactly once:
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)) # 45For a fixed i, the inner loop range(i + 1, n) runs n - (i + 1) times. Write out one row per outer value:
| i | inner range | inner iterations |
|---|---|---|
| 0 | 1 .. n-1 | n - 1 |
| 1 | 2 .. n-1 | n - 2 |
| ... | ... | ... |
| n-2 | n-1 .. n-1 | 1 |
| n-1 | empty | 0 |
The total is (n-1) + (n-2) + ... + 1 + 0. That is the arithmetic series up to n-1, so it equals n(n-1)/2.
The bars form a triangle that covers about half of an n × n square. That picture gives the name "triangular loop" and tells you the answer before you do any algebra: about n²/2 steps, which is Θ(n²).
A Repeatable Method
- Fix the outer variable and count the inner iterations as a formula in that variable, using the start, stop, and step rules.
- Write the total as a sum over every outer value.
- Match the sum to a known series and simplify.
The common triangular shapes all give a quadratic, but their exact counts differ by n:
| Inner loop | Sum | Exact count |
|---|---|---|
| `range(i)` | 0 + 1 + ... + (n-1) | n(n-1)/2 |
| `range(i + 1)` | 1 + 2 + ... + n | n(n+1)/2 |
| `range(i, n)` | n + (n-1) + ... + 1 | n(n+1)/2 |
| `range(i + 1, n)` | (n-1) + ... + 0 | n(n-1)/2 |
You can check the whole table at once:
def count(n, inner):
return sum(len(inner(i, n)) for i in range(n))
n = 50
assert count(n, lambda i, n: range(i)) == n * (n - 1) // 2
assert count(n, lambda i, n: range(i + 1)) == n * (n + 1) // 2
assert count(n, lambda i, n: range(i, n)) == n * (n + 1) // 2
assert count(n, lambda i, n: range(i + 1, n)) == n * (n - 1) // 2
print("all four formulas match")Common Errors
- Multiplying anyway. Writing n · n for a triangular loop gets the order of growth right but doubles the exact count. If a question asks for an exact count, sum the rows.
- Off-by-one in the last term. Ask whether the smallest row is 0 or 1 and whether the largest is n or n-1. Writing the first two and last two rows of the table settles it.
- Assuming every dependent loop is triangular. The inner count has to be linear in
ifor the arithmetic series to apply. If the inner loop isrange(i * i), the sum is 0² + 1² + ... + (n-1)², which is Θ(n³). If the inner loop halves, the sum is something else again. Always derive the formula for the inner count before you choose a series.
Exercise
How many times does steps += 1 run in for i in range(n): for j in range(i, n): steps += 1? Give the exact count and the order of growth.
Show answer
For each i the inner loop runs n - i times, so the total is n + (n-1) + ... + 1 = n(n+1)/2, which is Θ(n²). For n = 4 that gives 10.
Exercise
The loop for i in range(1, n + 1): for j in range(0, n, i): steps += 1 has an inner bound that depends on i. Why is the arithmetic series the wrong tool here?
Show answer
The inner loop runs ceil(n / i) times, which shrinks like n/i, not linearly in i. The total is about n(1 + 1/2 + ... + 1/n), a harmonic sum, so the loop is Θ(n log n), not Θ(n²).