3.1.2 · D3Complexity Analysis

Worked examples — Common complexities — O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(n!)

2,500 words11 min readBack to topic

Before anything, one word we lean on constantly:


The scenario matrix

Every complexity puzzle in this chapter is one of these cells. Each worked example below is tagged with the cell(s) it covers, so together they fill the whole grid.

Cell Case class What triggers it Answer class Example
A Fixed work, no loop over data direct index / arithmetic Ex 1
B Loop divides variable by constant n = n // 2, i *= 3 Ex 2
C Single pass, one op per element one for over the array Ex 3
D Sequential loops (the "add" trap) loop, then another loop still Ex 4
E Nested full loops (the "multiply") for inside for Ex 5
F Triangular nested loop inner starts at i still Ex 6
G Divide-and-conquer recursion split in half + linear merge Ex 7
H Branching recursion (double call) f(n-1)+f(n-1) Ex 8
I Degenerate / edge inputs , , empty class still holds Ex 9
J Real-world word problem forecast a runtime pick the class Ex 10
K Exam twist: mixed / misleading loop bound tied to a log careful reading Ex 11

Worked examples

Cell A — constant, no dependence on


Cell B — logarithmic: dividing, not subtracting

Figure — Common complexities — O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(n!)

Cell C — linear: one touch per element


Cell D — the sequential-loop trap (add, don't multiply)


Cell E — nested full loops: quadratic

Figure — Common complexities — O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(n!)

Cell F — triangular loop is still quadratic

Figure — Common complexities — O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(n!)

Cell G — divide-and-conquer:

Figure — Common complexities — O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(n!)

Cell H — branching recursion:

Figure — Common complexities — O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(n!)

Cell I — degenerate & edge inputs


Cell J — real-world forecast


Cell K — exam twist: loop bound tied to a log


Recall Quick self-test

Loop that does i *= 3 until i >= n — which class? ::: — divide-by-constant signature (base 3, but base is irrelevant). Triangular nested loop for j in range(i, n) — class? ::: — it's half the full grid; half of is still . fib(n) with two recursive calls — class? ::: — branching recursion doubles work. scan of at ops/s — runtime? ::: seconds (). Outer loop that doubles i, inner full range(n) — class? ::: outer × inner.