On 20 items, a 2n² algorithm beats a 100n one, 800 steps to 2,000. On a million items it is 20,000 times slower. The growth rate decides; the constants only move the crossover.
Drag the input size. Then give algorithm B a faster computer and watch how little the crossover moves. Then we build, piece by piece, the words for it: Big-O, Big-Omega, Big-Theta, the limit test, the growth ladder and the cost of a loop.
You need school algebra and a little Python. We build the rest from zero.
Based on Chapter 3, Growth of Functions, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Getting Started. Next: Divide and Conquer.
Illustrative costs: A takes 100n steps and B takes 2n² steps, divided by B's speed-up. Both axes are logarithmic: each grid line is ten times the last.
Chapter 0
See a small benchmark pick the wrong algorithm, and find the input size where the winner flips
Two functions sort an array. Algorithm A takes 100n steps for n items. Algorithm B takes 2n² steps. A colleague times both on 20 items: A takes 2,000 steps and B takes 800. "B is faster," they say. For 20 items, they are right.
| Items n | A: 100n | B: 2n² | B ÷ A |
|---|---|---|---|
| 20 | 2,000 | 800 | 0.4 |
| 50 | 5,000 | 5,000 | 1 |
| 1,000 | 100,000 | 2,000,000 | 20 |
| 1,000,000 | 108 | 2 × 1012 | 20,000 |
The last column is n divided by 50, and it grows without end. The 100 and the 2 are constant factors: numbers set by the hardware, the language and the compiler. The growth rate, linear against quadratic, belongs to the algorithm itself. This chapter of CLRS gives us exact words for growth rates.
Where do the two costs meet? Call the quadratic cost a·n² and the linear cost b·n, where a and b are the constant factors. The crossover is the size n* where the two costs are equal.
n-star equals b over a.
Set a times n squared equal to b times n. Divide both sides by a times n. What is left is n-star = b / a. Below n-star the quadratic algorithm is cheaper; above it the linear one wins, for good.
A has b = 100 and B has a = 2, so n* = 100 / 2 = 50. If B runs 100 times faster, its a drops to 0.02 and n* = 5,000. The speed-up moved the crossover. It did not change the winner past it.
Pink is the quadratic cost a·n². Blue is the linear cost b·n. Drag either constant and watch where the curves cross.
Illustrative costs on linear axes, n from 0 to 250.
Real libraries use the crossover. Python's built-in sort (Timsort) is O(n log n) overall. But it sorts short runs, of up to 64 items, with insertion sort, which is quadratic. Below the crossover the simple method is faster.
The failure: a choice made on a small benchmark. Symptom: the code is fast in tests and slow in production. Measure: time it at n, 2n and 4n. If the time doubles each step, it is linear; if it grows four times, it is quadratic. Fix: choose by growth rate at the size you will run in production.
Chapter 1
Find a multiplier and a starting size that keep a function under a ceiling forever
"Grows no faster than" needs an exact meaning. Call the function we study f(n), for example the steps an algorithm takes on n items. Call the simpler function we compare it with g(n), for example n². We allow a fixed multiplier c, and we ignore all sizes below a fixed starting size n0.
f of n is at most c times g of n, for every n from n-nought on.
Pick a multiplier c and a starting size n0. From n0 on, f(n) must never rise above c times g(n). If one such pair exists, we write f(n) = O(g(n)), said "f is big-O of g".
f(n) = 2n² + 3n + 1 and g(n) = n². For n ≥ 1, 3n ≤ 3n² and 1 ≤ n², so f(n) ≤ 6n²: c = 6 and n0 = 1 work. A tighter c = 3 fails at n = 3 (28 > 27) and holds from n = 4 (45 ≤ 48).
The pair (c, n0) is a witness: proof that the ceiling exists. You need one witness, not the best one. Divide both sides by n² to see every witness at once: the bound says 2 + 3/n + 1/n² ≤ c. That ratio falls toward 2 as n grows.
Blue is the ratio f(n)/g(n). Warm is your multiplier c. Right of the purple line, blue must stay under warm. Drag c down toward 2 and watch how far n0 must move.
f(n) = 2n² + 3n + 1. The device checks every whole n from n0 to 100,000.
Any c above 2 works with a late enough start: c = 3 from n = 4, c = 2.5 from n = 7, c = 2.1 from n = 31. No c of 2 or less works, because the ratio stays above 2 for every n. Switch g to n: the ratio is 2n + 3 + 1/n, it grows without end, and no c can cap it. So 2n² + 3n + 1 is not O(n).
Big-O is a ceiling, not a match. 3n = O(n²) is true, with c = 3 and n0 = 1, but loose. The "=" means "belongs to": O(g) is the set of functions under some ceiling c·g. So it reads one way only.
The failure: a witness checked at a few sizes. Symptom: a proof picks c = 2 for this f because 2n² looks right. Measure: compute the largest ratio f(n)/g(n) for n ≥ n0. Fix: choose c above that largest ratio, as the Code Lab does.
Chapter 2
Flip the inequality to say a function grows at least as fast as another
A ceiling says the cost will not be worse. It says nothing about better. Merge sort is O(n log n), and also O(n²). Could it be faster than n log n? For that question we need a floor. Keep the same names: f(n) the function we study, g(n) the comparison, a fixed multiplier c above zero, a start n0.
f of n is at least c times g of n, for every n from n-nought on.
Pick a multiplier c and a start n0. From n0 on, f(n) must never fall below c times g(n). If such a pair exists, we write f(n) = Ω(g(n)), said "f is big-Omega of g".
f(n) = 2n² + 3n. The term 3n is never negative, so drop it: f(n) ≥ 2n². That is c = 2 and n0 = 1. At n = 10: f = 230 and c·g = 200.
For a floor, the trick reverses. To build a ceiling we inflated small terms; to build a floor we drop the positive ones. A subtracted term needs care. For n² − 100n, we need 100n ≤ n²/2, which first holds at n = 200. So c = 1/2 works from n0 = 200.
Blue is the ratio f(n)/g(n). Warm is your floor c. Right of the purple line, blue must stay on or above warm. Raise c past the ratio's limit and see where it fails.
g(n) = n² in both cases. The device checks every whole n from n0 to 100,000.
For 2n² + 3n the ratio is 2 + 3/n. It starts at 5 and sinks toward 2. So with n0 = 1, the largest valid c is 2. A floor of 2.5 holds only up to n = 6; a floor of 3 fails from n = 4. Beyond the start, the floor can never pass the ratio's limit.
The two bounds mirror each other. f = O(g) exactly when g = Ω(f): turn f ≤ c·g around and you get g ≥ (1/c)·f. A lower bound can describe one algorithm (insertion sort is Ω(n²) in the worst case) or a whole problem. Every comparison sort needs Ω(n log n) comparisons in the worst case, so merge sort cannot be beaten by much.
The failure: a floor read off a small n. Symptom: someone claims 2n² + 3n = Ω(n²) with c = 5, because 5 works at n = 1. Measure: check the ratio at large n. Fix: keep c at or under the limit, here 2.
Chapter 3
Trap a function between a floor and a ceiling to say it grows at exactly the rate of another
When the ceiling and the floor use the same g, we know the growth rate exactly. Use two multipliers: a floor multiplier c1 and a ceiling multiplier c2, both fixed and above zero, and one start n0.
c-one times g of n is at most f of n, which is at most c-two times g of n, for every n from n-nought on.
Draw a floor c1·g(n) and a ceiling c2·g(n). From n0 on, f(n) must stay between them. If such a triple exists, f(n) = Θ(g(n)), said "f is big-Theta of g".
f(n) = n²/2 − 3n. The ceiling c2 = 1/2 holds for every n, since we only subtract. The floor c1 = 1/4 needs 3n ≤ n²/4, so n0 = 12. At n = 12, f = 72 − 36 = 36 and the floor is 144/4 = 36: they touch. At n = 11, f = 27.5 is under the floor 30.25.
Blue is the ratio f(n)/g(n). The two warm lines are c1 and c2. Right of the purple line, blue must stay inside the band. Squeeze the band toward the ratio's limit.
g(n) = n². The device checks every whole n from n0 to 100,000.
Switch to 2n² + 3n. Its ratio 2 + 3/n sits above 2 for every n. So the floor c1 = 2 works from n = 1, but the ceiling must be strictly above 2: c2 = 2 fails at every n. With c2 = 2.1 the sandwich holds from n = 30; with c2 = 5, from n = 1.
f = Θ(g) exactly when f = O(g) and f = Ω(g). The leading term rule follows: a polynomial whose top term is a·nk, with a above zero, is Θ(nk). So 7n³ − 2n² + 100n − 42 = Θ(n³).
One identity returns in the sorting chapters: log(n!) = Θ(n log n). Ceiling: log(n!) is a sum of n logs, each at most log n. Floor: keep only the top n/2 terms, each at least log(n/2).
The failure: a Theta claim built on one side only. Symptom: "3n = Θ(n²)". Measure: the ratio 3n/n² = 3/n sinks to 0, so no floor c1 above zero survives. Fix: write O(n²), or the tight Θ(n).
Chapter 4
Divide one function by the other and watch where the ratio goes
Big-O allows a tie: 3n² = O(n²). Sometimes we want to say "strictly slower", with no tie. Little-o says it: f(n) = o(g(n)) when, for every c above zero, f(n) < c·g(n) from some n0 on. Big-O asks for one c; little-o must beat them all, even c = 0.001.
The easy test is a ratio. Divide f(n) by g(n) and let n grow without end. The value the ratio settles to is its limit.
The limit, as n goes to infinity, of f of n over g of n, equals zero.
Divide f(n) by g(n) at larger and larger n. If the ratio sinks toward zero, f(n) = o(g(n)): f grows strictly slower than g.
f(n) = 3n + 5 and g(n) = n². At n = 10 the ratio is 35/100 = 0.35. At n = 100 it is 305/10,000 = 0.0305. At n = 1,000 it is 0.003. It heads to 0, so 3n + 5 = o(n²).
The limit sorts every common pair into one of three cases. Little-omega, ω, is the mirror of little-o: strictly faster.
| Limit of f/g | Verdict | Like numbers | Example |
|---|---|---|---|
| 0 | f = o(g), so also O(g) | f < g | n = o(n²) |
| a number above 0 | f = Θ(g) | f = g | 3n² = Θ(n²), limit 3 |
| ∞ | f = ω(g), so also Ω(g) | f > g | n² = ω(n) |
Pick a pair. Blue is the ratio f(n)/g(n) as n runs from 1 to a million. Press Play to grow n and read where the ratio heads.
The vertical axis is log₁₀ of the ratio, so 0 means equal, −3 means a thousand times smaller. The n¹⁰⁰ pair runs n from 1 to 2,000 so the turn shows.
Two facts come out of the pairs. Any power of log loses to any power of n: at n = 106, log₂n / √n = 20/1,000 = 0.02. Any polynomial loses to any exponential, and the base of an exponential matters: 2ⁿ/3ⁿ = (2/3)ⁿ goes to 0, so 2ⁿ = o(3ⁿ).
Not every pair has a verdict. Take f(n) = n for even n and n² for odd n, against g(n) = n1.5. The ratio jumps between 0 and ∞ forever, so f is neither O(g) nor Ω(g).
The failure: a verdict read at small n. Symptom: at n = 100, n¹⁰⁰ = 10²⁰⁰ dwarfs 2¹⁰⁰ ≈ 1.3 × 10³⁰, so someone says the polynomial grows faster. Measure: compare at larger n; the exponential takes over from n = 997. Fix: use the limit, not a sample.
Chapter 5
Race nine growth classes on one scale and find the cliff between polynomial and exponential
Most algorithms you will meet sit on one of nine rungs. Each rung grows strictly faster than the one before it, in the little-o sense of Chapter 4. The device puts all nine on one logarithmic scale, so a bar one unit longer means ten times more steps.
Each bar is the step count of one class at size n, as a power of ten. The purple line is the age of the universe at a billion steps per second. Drag n from 2 to 1,000.
Times assume 109 simple steps per second and one step per unit of cost. The age of the universe, about 13.8 billion years, is about 4.4 × 1026 such steps. Logs are base 2.
| Class | n = 10 | n = 100 | n = 1,000 | Example |
|---|---|---|---|---|
| 1, constant | 1 | 1 | 1 | read an array cell by index |
| log n | 3.3 | 6.6 | 10.0 | binary search |
| √n | 3.2 | 10 | 31.6 | trial division up to √n |
| n | 10 | 100 | 1,000 | one pass over the data |
| n log n | 33 | 664 | 9,966 | merge sort |
| n² | 100 | 10,000 | 106 | insertion sort, worst case |
| n³ | 1,000 | 106 | 109 | schoolbook matrix multiply |
| 2ⁿ | 1,024 | 1.3 × 1030 | 1.1 × 10301 | try every subset |
| n! | 3,628,800 | 9.3 × 10157 | 4.0 × 102567 | try every ordering |
Run them at a billion steps per second. 2ⁿ takes 1 microsecond at n = 10 and 1 second at n = 30. It takes 13 days at n = 50 and 40 trillion years at n = 100. n! takes 3.6 milliseconds at n = 10 and 77 years at n = 20. A polynomial class, nk for a fixed k, stays usable; an exponential one hits a wall within a few dozen items. That wall is why computer science calls polynomial algorithms efficient.
The bottom rungs are almost free. From a million items to a billion, log₂n moves from 20 to 30. A binary search over 1080 items, about the number of atoms in the observable universe, needs at most 266 comparisons.
The base of a log does not matter inside O. logan = logbn / logba, and logba is a constant. For example, log₂n is about 3.32 times log₁₀n. So we write O(log n) with no base. The base of an exponential does matter, as 2ⁿ = o(3ⁿ) showed.
The failure: brute force that passed its test. Symptom: trying every subset works on 20 items in a millisecond and never finishes on 60. Measure: add one item and time it again; if the time doubles, the cost is exponential. Fix: a polynomial method, such as dynamic programming, or limits on n.
Chapter 6
Turn a time limit into the largest input each growth class can finish
A request must answer in one second. Your machine does about 108 simple steps per second. How large can the input be? Flip the question of Chapter 5: fix the time and solve for n. Call the step count f(n), the machine's speed s in steps per second, and the time budget T in seconds.
n-star is the largest n for which f of n is at most s times T.
Multiply the speed s by the time T to get the budget in steps. Then find the biggest n whose step count f(n) still fits inside it. That n is n-star.
s = 108 and T = 1 s give a budget of 108 steps. For f(n) = n², n* = √108 = 10,000. For f(n) = n!, 11! = 39,916,800 fits and 12! = 479,001,600 does not, so n* = 11.
Each bar is n* for one class, on a log scale. Pick a budget, then make the machine faster. Watch which bars move and which barely do.
The device finds each n* exactly, by doubling and then halving the search range on whole numbers. log is base 2.
| Class | 1 second | 1 minute | 1 hour |
|---|---|---|---|
| n | 108 | 6 × 109 | 3.6 × 1011 |
| n log n | 4,523,071 | 216,677,120 | 1.08 × 1010 |
| n² | 10,000 | 77,459 | 600,000 |
| n³ | 464 | 1,817 | 7,113 |
| 2ⁿ | 26 | 32 | 38 |
| n! | 11 | 12 | 14 |
An hour instead of a second is 3,600 times more budget. It gives n² 60 times more items, and 2ⁿ twelve more. So read the problem's limit on n first, and let it pick the class:
| Limit on n | Class that fits in about a second | Typical method |
|---|---|---|
| n ≤ 11 | n! | try every ordering |
| n ≤ 25 | 2ⁿ | try every subset, bitmask DP |
| n ≤ 450 | n³ | triple loop, Floyd-Warshall |
| n ≤ 10,000 | n² | all pairs, 2-D table |
| n ≤ 106 | n log n | sort, heap, divide and conquer |
| n ≤ 108 | n | one pass, two pointers, hash map |
The failure: the wrong class for the size. Symptom: an all-pairs check on 106 items. Measure: 1012 steps at 108 per second is 10,000 seconds. Fix: sort first, or hash, to reach n log n or n.
Chapter 7
Count how often the inner line runs, close the sum, and read off the growth class
To find the cost of code, count how many times its innermost line runs. A single loop over n items runs its body n times: Θ(n). Two rules combine the pieces. Nested loops multiply. Blocks in sequence add, and the larger term wins, because max(f, g) ≤ f + g ≤ 2·max(f, g).
Pick a loop. The inner line is count += 1. Press Play: each cell lights when it runs. Compare the count with the formula under the grid.
Each cell is one run of the innermost line. Row i holds the runs made while the outer loop is at i.
The all-pairs loop is the one in a duplicate check: for each i, the inner loop runs j from i + 1 to n − 1. So row i has n − 1 − i cells. Call the row size i and add the rows up.
The sum over i from zero to n minus one of i equals n times n minus one, over two.
Write the rows 0 + 1 + … + (n − 1). Write the same sum backwards under it. Each column adds to n − 1, and there are n columns, so twice the sum is n(n − 1). Halve it.
n = 12: 12 × 11 / 2 = 66 checks. n = 1,000: 499,500 checks. Double n to 2,000 and the count grows to 1,999,000, about 4 times. That factor of 4 per doubling is Θ(n²).
Binary search halves a window until it is empty. Call the window size n. The window goes n, about n/2, about n/4, down to 1, and each size costs one probe. Count the probes:
Probes equals the floor of log base two of n, plus one.
Halve n again and again, rounding down, and count the halvings until 1 is left. Add one for the final window. That count is the number of probes.
n = 1,000: log₂1,000 = 9.97 and the floor is 9, so 10 probes. n = 1,024 gives exactly 10, so 11 probes. A million items take 20.
Put a halving loop inside a loop over n and the costs multiply: Θ(n log n). A recursive function gives a recurrence, such as T(n) = 2T(n/2) + n for merge sort, which the next lesson solves.
The failure: a hidden loop. Symptom: result += word in a loop, or if x not in seen_list, looks linear and is quadratic, because each line copies or scans everything so far. Measure: time n and 2n; a factor of 4 means quadratic. Fix: " ".join(words) and a set.
for i in range(n): j = 1; while j < n: j *= 2?Chapter 8
Keep the bound apart from the case, the step from the sequence, and time from space
The most common mistake is to treat O as "worst case" and Ω as "best case". They are separate questions. The case picks which inputs you measure: the best, the worst, or an average over random inputs. The bound (O, Ω, Θ) then describes how that cost grows.
The dots are real comparison counts of insertion sort. Pick the input order and drag n. Blue is n − 1; warm is n(n − 1)/2.
The device runs insertion sort and counts each key comparison. Random inputs use a fixed seed, so each n always gives the same count.
On sorted input, insertion sort makes n − 1 comparisons: its best case is Θ(n). On reversed input it makes n(n − 1)/2: its worst case is Θ(n²). On random input it makes about n²/4, still Θ(n²). So "insertion sort is Θ(n²)" is false as a statement about every input. Say "its worst-case time is Θ(n²)".
| Pitfall | What is true | Example |
|---|---|---|
| O(n) means n steps | O hides constants and smaller terms | 7n + 42 = O(n) |
| Same class, same speed | constants and memory access still differ | Strassen's n2.81 method loses to the n³ method on small matrices |
| Amortized is average | amortized bounds the total of any sequence | a doubling array: n appends copy fewer than 2n items in total |
| Only time counts | space has its own bound | merge sort needs O(n) extra; heapsort O(1) |
| One size variable | keep every size that matters | breadth-first search is O(V + E) |
| Depth is time | depth bounds the stack, not the work | naive Fibonacci: depth n, calls growing about 1.618 times per step |
| A true bound is a good bound | give the tightest bound you can prove | insertion sort is O(n!), true and useless |
Amortized cost needs one more sentence. A dynamic array that doubles when full copies 1, then 2, then 4 items, and so on. Over n appends the copies add to less than 2n. So each append costs O(1) amortized: averaged over the sequence, with no random inputs assumed.
The failure: a worst-case spike under a deadline. Symptom: a hash table with O(1) average lookups misses a 10 ms limit now and then. Measure: log the slowest 0.1% of operations, not the mean. Fix: if you need a guarantee per operation, use a structure with a worst-case bound, such as a balanced tree with O(log n).
Chapter 9
Keep the five notations, the numbers, the checks and the core code on one page
Asymptotic notation keeps the growth rate and drops the constants. Big-O is a ceiling, Big-Omega a floor, Big-Theta both; a witness (c, n0) proves each one. Little-o and little-omega are strict, and the limit of f/g decides them. Loops become sums; sums become classes; the class and the size limit pick the algorithm.
| Notation | Definition | Like numbers |
|---|---|---|
| f = O(g) | some c > 0 and n0 with f(n) ≤ c·g(n) for all n ≥ n0 | ≤ |
| f = Ω(g) | some c > 0 and n0 with f(n) ≥ c·g(n) for all n ≥ n0 | ≥ |
| f = Θ(g) | some c1, c2 > 0 and n0 with c1g(n) ≤ f(n) ≤ c2g(n) | = |
| f = o(g) | for every c > 0, some n0 with f(n) < c·g(n); limit of f/g is 0 | < |
| f = ω(g) | for every c > 0, some n0 with f(n) > c·g(n); limit of f/g is ∞ | > |
| What | Number | Why it matters |
|---|---|---|
| 100n against 2n² | crossover at n = 50; B is 20,000 times slower at 106 | constants move the crossover, not the winner |
| 2n² + 3n + 1 = O(n²) | c = 6 from 1; c = 3 from 4; c = 2.1 from 31; no c ≤ 2 | c must exceed the leading coefficient |
| 2n² + 3n = Ω(n²) | largest c with n0 = 1 is 2 | a floor cannot pass the limit |
| n²/2 − 3n = Θ(n²) | c1 = 1/4, c2 = 1/2, n0 = 12 | CLRS's sandwich |
| 1 second at 108 steps | n²: 10,000; n³: 464; 2ⁿ: 26; n!: 11 | the cliff at the exponential |
| All pairs, n = 1,000 | 499,500 checks | n(n − 1)/2 |
| Binary search, n = 106 | 20 probes | ⌊log₂n⌋ + 1 |
pythonimport math def min_c(f, g, n0, N=100_000): # smallest multiplier c with f(n) <= c*g(n) for n0..N: the largest ratio on the tail return max(f(n) / g(n) for n in range(n0, N + 1)) def max_feasible(cost, budget): # largest n with cost(n) <= budget: double to bracket it, then halve lo, hi = 1, 2 while cost(hi) <= budget: lo, hi = hi, hi * 2 while hi - lo > 1: mid = (lo + hi) // 2 lo, hi = (mid, hi) if cost(mid) <= budget else (lo, mid) return lo f = lambda n: 2*n*n + 3*n + 1 print(min_c(f, lambda n: n*n, 1)) # 6.0 print(min_c(f, lambda n: n*n, 31) <= 2.1) # True print(max_feasible(math.factorial, 10**8)) # 11
| Operation | Cost | What it means |
|---|---|---|
| Self-attention, length n, width d | O(n²d) time | twice the context, four times the attention work |
| FlashAttention (Dao et al., 2022) | O(n²d) time, O(n) extra memory | same time class; it never stores the n × n score matrix |
| One new token with a KV cache | O(nd) per layer | attend over n stored keys; no recompute of old tokens |
| Embedding lookup | O(d) per token | an array index into a V × d table; the vocabulary size V does not matter |
| Adam update, p parameters | O(p) time, 2p extra memory | two running averages per parameter |
Now press Present or Teach. Explain from memory what a witness (c, n0) is. Say why c must be above 2 for 2n² + 3n + 1, and why a faster computer cannot save 2ⁿ. Then go back to the race, give B a 100× machine, and say where the crossover moves.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 3, Growth of Functions. The definitions and the n²/2 − 3n example follow the book; the devices, numbers and witnesses on this page are our own.