Sub topic 5
Nested Loops: Multiplying Costs
This chapter assumes you can read Python for and while loops, that you can count the iterations of a single loop from its range arguments, and that you know how to add the costs of blocks that run one after another. Those topics come from the earlier chapters. Here we put one loop inside another and work out the total cost.
The core rule is short. If the inner loop runs the same number of times on every pass of the outer loop, the total is the outer count times the inner count. Most mistakes with nested loops come from applying this rule when its condition does not hold, or from skipping the work that sits outside the inner loop.
The Product Rule
Take an outer loop that runs n times. Inside it sits an inner loop that runs m times. The inner loop's bounds do not mention the outer variable. Each pass of the outer loop therefore runs the full inner loop, m iterations, and there are n such passes.
def count_grid(n, m):
steps = 0
for i in range(n):
for j in range(m):
steps += 1
return steps
print(count_grid(4, 5)) # 20The innermost body runs n * m times, so count_grid(4, 5) returns 20. The inner loop is independent of the outer one because range(m) gives the same sequence whatever the value of i. That independence is the only condition the product rule needs.
The table below lists which (i, j) pairs the body visits for n = 3 and m = 4. Each row is one outer pass, and every row has the same length.
| Outer pass `i` | Inner values `j` | Body runs |
|---|---|---|
| 0 | 0, 1, 2, 3 | 4 |
| 1 | 0, 1, 2, 3 | 4 |
| 2 | 0, 1, 2, 3 | 4 |
| Total | 3 × 4 = 12 |
The total is a rectangle of n rows and m columns. In the next chapters the rows will have different lengths, and the rectangle becomes a triangle.
Combining the Product Rule with Exact Bounds
The product rule works with any exact iteration count, including ones from range(a, b, s). Count each loop with the formula from the bounds chapter, then multiply.
import math
def count_strided(n, m):
steps = 0
for i in range(n):
for j in range(0, m, 3):
steps += 1
return steps
n, m = 6, 10
print(count_strided(n, m)) # 24
print(n * math.ceil(m / 3)) # 24The inner loop visits j = 0, 3, 6, 9, which is ceil(10 / 3) = 4 iterations. Six outer passes give 24. The stride affects only the inner factor and has no effect on the multiplication.
The rule also extends to any depth. Three independent loops with counts n, m, and p run their innermost body n * m * p times. Matrix multiplication is the standard example. For an n × k matrix times a k × m matrix, every one of the n * m output cells needs k multiply-add operations.
def matmul(A, B):
n, k, m = len(A), len(B), len(B[0])
C = [[0] * m for _ in range(n)]
mults = 0
for i in range(n):
for j in range(m):
for t in range(k):
C[i][j] += A[i][t] * B[t][j]
mults += 1
return C, mults
A = [[1, 2, 3],
[4, 5, 6]] # 2 x 3
B = [[1, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 1, 1]] # 3 x 4
C, mults = matmul(A, B)
print(C) # [[1, 2, 3, 6], [4, 5, 6, 15]]
print(mults) # 24 = 2 * 4 * 3When all three dimensions equal n, the count is n³. Most people remember this result as "matrix multiplication is cubic," and the product rule is where it comes from.
Work Outside the Inner Loop
The body of the outer loop often holds more than the inner loop. It may set up a variable before the inner loop and store a result after it. These statements run once per outer pass, not once per inner iteration. Find the cost of one outer pass using the addition rule for sequential code, then multiply that cost by the number of outer passes.
def count_rows(n, m):
steps = 0
for i in range(n):
steps += 1 # set up the row: 1 step
for j in range(m):
steps += 1 # inner body: m steps
steps += 1 # finish the row: 1 step
return steps
print(count_rows(4, 5)) # 28
print(4 * (5 + 2)) # 28One outer pass costs 1 + m + 1 = m + 2 steps, so the total is n(m + 2) = nm + 2n. The 2n term is real work. If m is a small constant, it can make up a large share of the total. For example, with m = 1 it is two-thirds of all the steps. When m grows, the nm term takes over, and the chapter on order of growth will show how to drop the smaller terms properly.
The general method has two steps:
- Find the cost of one pass of the outer body by adding up its parts. One of those parts is the full cost of the inner loop.
- If that per-pass cost is the same on every pass, multiply it by the number of outer passes.
When "Nested" Does Not Mean "Quadratic"
Two nested loops do not always give n². The total is the product of the two actual counts, and either count can be a constant or a different variable.
Constant inner loops. Grid code often checks the four neighbors of every cell:
def count_neighbor_checks(grid):
rows, cols = len(grid), len(grid[0])
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
checks = 0
for r in range(rows):
for c in range(cols):
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
checks += 1
# the bounds test itself runs 4 times per cell
return checks
grid = [[0] * 5 for _ in range(3)]
print(count_neighbor_checks(grid)) # 22 in-bounds neighborsThe code has three loop levels, but the innermost loop always runs 4 times. The bounds test runs 4 × rows × cols times, which is 4N for N cells. That count is linear in the number of cells. Some tests fail at the edges, so only 22 neighbors are in bounds for a 3 × 5 grid, but all 4 × 15 = 60 tests still run. Count the tests, because a failed test costs about as much as a passing one.
Different variables. count_grid(n, m) costs nm, not n². If you rewrite nm as n², you lose information. When m stays small, say a fixed number of columns, the cost is linear in n. When m grows with the data, you need both variables. Keep each input size as its own symbol until you know how the sizes relate.
Edge Cases That Break the Rule
The product rule assumes that each outer pass runs a complete, fresh inner loop. The examples below check that assumption.
An inner `while` loop that never resets
A for loop over range(m) creates a fresh iterator every time the outer loop reaches it. A while loop has no such reset. If you initialize its counter outside the outer loop, its state carries over from one pass to the next.
def count_no_reset(n, m):
steps = 0
j = 0 # initialized once, outside the outer loop
for i in range(n):
while j < m:
j += 1
steps += 1
return steps
print(count_no_reset(4, 5)) # 5, not 20The first outer pass uses up all m inner iterations. Every later pass finds j == m and skips the inner body. The total is m body steps plus n failed loop tests, so the cost is n + m, not nm. This pattern is deliberate in two-pointer algorithms, where it is the reason they run in linear time. It also turns up by accident when someone moves j = 0 to the wrong line. To find the real count, look at where the inner loop's state is initialized.
Reusing the loop variable
Python lets you reuse a name in an inner loop. This is bad style, but it does not change the count:
def count_shadowed(n, m):
steps = 0
for i in range(n):
for i in range(m): # overwrites i, but the outer iterator is unaffected
steps += 1
return steps
print(count_shadowed(4, 5)) # 20The outer for gets its next value from its own range iterator, not from the name i, so it still runs n times. A while loop is different. If the outer loop is while i < n and the inner loop also changes i, the counts become linked, and you have to trace them by hand.
Empty ranges
If n = 0 or m = 0, the body runs 0 times, and the product rule gives the right answer. The loop tests still run, though. With m = 0, every outer pass still checks the inner loop's condition once and finds it false. count_rows(n, 0) returns 2n, not 0. For most purposes this overhead does not matter, but it explains why a nested loop over empty inner data still takes time proportional to n.
Inner loops that exit early
A break or return inside the inner loop means the inner count can differ from pass to pass. The product n × m then becomes an upper bound rather than an exact count. The chapter on early exits deals with this case through best-case and worst-case analysis.
Summary of the Rule
| Structure | Exact body count | Condition |
|---|---|---|
| `for i in range(n): for j in range(m)` | `n * m` | inner bounds do not depend on `i` |
| Three independent loops `n`, `m`, `p` | `n * m * p` | no bound depends on an outer variable |
| Outer body = setup + inner(`m`) + teardown | `n * (m + c)` | `c` constant steps per pass |
| Inner loop over a fixed list of size 4 | `4n` | inner size is constant |
| Inner `while` with state set outside | `m` body steps, plus `n` tests | inner state not reset |
If the inner bound depends on the outer variable, as in range(i + 1, n), the passes no longer have equal cost and simple multiplication fails. The next two chapters cover the series and the counting method that handle that case.
Exercise
How many times does the line total += 1 run? Give an exact formula in n and m, and evaluate it for n = 7, m = 20.
def f(n, m):
total = 0
for i in range(1, n, 2):
for j in range(5, m, 5):
total += 1
return total
Show answer
The outer loop runs ceil((n - 1) / 2) times, and the inner loop runs ceil((m - 5) / 5) times on every pass, independent of i. The total is ceil((n - 1) / 2) * ceil((m - 5) / 5). For n = 7, m = 20, the outer loop visits i = 1, 3, 5 (3 passes), the inner loop visits j = 5, 10, 15 (3 iterations), and the total is 9.
Exercise
A function loops over each of n customers. For each customer it does 3 constant-time steps of setup, then loops over that customer's last 12 orders (always exactly 12) doing 2 steps per order, then does 1 final step. Write the exact step count and say whether the function is quadratic in n.
Show answer
One outer pass costs 3 + 12 * 2 + 1 = 28 steps, so the total is 28n. The inner loop has a constant bound, so the cost is linear in n, not quadratic.
Exercise
A programmer moves j = 0 above the outer loop in a nested loop of the form for i in range(n): while j < m: ... j += 1. Before the change the body ran n * m times. How many times does it run after the change, and why?
Show answer
It runs m times in total. The first outer pass increases j to m, and every later pass finds j < m false and skips the body. The remaining cost is about n loop-condition tests, so the total work is roughly n + m.