Growth of Functions

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.

Race a linear algorithm against a quadratic one

20

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

The Crossover

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 nA: 100nB: 2n²B ÷ A
202,0008000.4
505,0005,0001
1,000100,0002,000,00020
1,000,0001082 × 101220,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.

Say it aloud

n-star equals b over a.

n*
n-star the crossover: the input size where both algorithms take the same number of steps.
b
b the constant factor of the linear algorithm: steps per item.
a
a the constant factor of the quadratic algorithm.
In plain words

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.

With numbers

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.

Move the constants, watch the crossover

Pink is the quadratic cost a·n². Blue is the linear cost b·n. Drag either constant and watch where the curves cross.

2.0
100

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.

The road

  1. Big-O: a ceiling on growth, with a witness c and n0.
  2. Big-Omega: a floor on growth.
  3. Big-Theta: a ceiling and a floor together.
  4. Little-o and little-omega: strictly slower or faster, by the limit test.
  5. The growth ladder: nine classes on one scale (the showcase).
  6. The budget: the largest input a second, a minute or an hour affords.
  7. Reading code: from loops to sums to a growth class.
  8. Pitfalls: best and worst case, hidden loops, amortized cost.
  9. The field guide: definitions, numbers, code and the credit.
Algorithm X takes 5n² + 100 steps. Algorithm Y takes 1000n + 5000 steps. For which n is X faster?

Chapter 1

Big-O: A Ceiling on Growth

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.

Say it aloud

f of n is at most c times g of n, for every n from n-nought on.

f(n)
f of n the function we study: here 2n² + 3n + 1 steps.
≤
is at most f may touch the ceiling but never go above it.
c
c a fixed positive multiplier. It cannot change with n.
g(n)
g of n the comparison function: here n².
n ≥ n0
for every n from n-nought on sizes below n0 do not count.
In plain words

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".

With numbers

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.

Hunt for a witness

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.

3.0
1

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.

Is 5n³ = O(n²)?

Chapter 2

Big-Omega: A Floor on Growth

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.

Say it aloud

f of n is at least c times g of n, for every n from n-nought on.

f(n)
f of n the function we study: here 2n² + 3n.
≥
is at least f may touch the floor but never drop below it.
c
c a fixed multiplier above zero. It can be tiny, like 0.01.
g(n)
g of n the comparison function: here n².
n ≥ n0
for every n from n-nought on small sizes do not count.
In plain words

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".

With numbers

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.

Push the floor up until it breaks

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.

2.00
1

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.

With n0 = 1, what is the largest c that makes 2n² + 3n ≥ c·n² hold for every n?

Chapter 3

Big-Theta: The Sandwich

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.

Say it aloud

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.

c1
c-one the floor multiplier.
g(n)
g of n the comparison function: here n².
f(n)
f of n the function we study: here CLRS's n²/2 − 3n.
c2
c-two the ceiling multiplier.
n ≥ n0
for every n from n-nought on one start for both sides.
In plain words

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".

With numbers

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.

Close the sandwich

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.

0.25
0.50
12

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).

Which statement is true?

Chapter 4

Little-o and Little-omega: Strictly Slower, Strictly Faster

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.

Say it aloud

The limit, as n goes to infinity, of f of n over g of n, equals zero.

limn→∞
the limit as n goes to infinity the value the ratio settles to as n grows past every bound.
f(n) / g(n)
f of n over g of n how many times bigger f is than g at size n.
0
zero f becomes a vanishing fraction of g.
In plain words

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.

With numbers

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/gVerdictLike numbersExample
0f = o(g), so also O(g)f < gn = o(n²)
a number above 0f = Θ(g)f = g3n² = Θ(n²), limit 3
∞f = ω(g), so also Ω(g)f > gn² = ω(n)

Watch the ratio decide

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.

Which notation states "n log n grows strictly slower than n²"?

Chapter 5

The Growth Ladder

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.

Climb the ladder

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.

30

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.

Classn = 10n = 100n = 1,000Example
1, constant111read an array cell by index
log n3.36.610.0binary search
√n3.21031.6trial division up to √n
n101001,000one pass over the data
n log n336649,966merge sort
n²10010,000106insertion sort, worst case
n³1,000106109schoolbook matrix multiply
2ⁿ1,0241.3 × 10301.1 × 10301try every subset
n!3,628,8009.3 × 101574.0 × 102567try 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.

Order these from slowest growth to fastest: n², 2ⁿ, n log n, log n, n!, n, 1.

Chapter 6

The Budget: How Big an Input Can You Afford?

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.

Say it aloud

n-star is the largest n for which f of n is at most s times T.

n*
n-star the largest input that finishes in time.
f(n)
f of n the steps the algorithm takes on n items.
s
s the speed: steps per second, here 108.
T
T the time budget in seconds. s·T is the budget in steps.
In plain words

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.

With numbers

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.

Spend a time budget

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.

10⁸/s

The device finds each n* exactly, by doubling and then halving the search range on whole numbers. log is base 2.

Class1 second1 minute1 hour
n1086 × 1093.6 × 1011
n log n4,523,071216,677,1201.08 × 1010
n²10,00077,459600,000
n³4641,8177,113
2ⁿ263238
n!111214

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 nClass that fits in about a secondTypical method
n ≤ 11n!try every ordering
n ≤ 252ⁿtry every subset, bitmask DP
n ≤ 450n³triple loop, Floyd-Warshall
n ≤ 10,000n²all pairs, 2-D table
n ≤ 106n log nsort, heap, divide and conquer
n ≤ 108none 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.

Your budget is 108 steps and n = 106. Which classes finish?

Chapter 7

Reading Code: Loops Become Sums

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).

Count the inner line

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.


    
12

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.

Say it aloud

The sum over i from zero to n minus one of i equals n times n minus one, over two.

Σi=0n−1
the sum over i from zero to n minus one add one term for each row.
i
i the number of inner runs in one row: 0, 1, up to n − 1.
n(n − 1) / 2
n times n minus one, over two the total runs: the number of pairs.
In plain words

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.

With numbers

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:

Say it aloud

Probes equals the floor of log base two of n, plus one.

probes
probes comparisons when the target is larger than every item, the worst case.
⌊log₂ n⌋
the floor of log base two of n how many times you can halve n before it drops below 2, rounded down.
1
plus one the last window, of size 1, still costs a probe.
In plain words

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.

With numbers

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.

What is the cost of: for i in range(n): j = 1; while j < n: j *= 2?

Chapter 8

Pitfalls

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.

Sort three kinds of input

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.

100

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²)".

PitfallWhat is trueExample
O(n) means n stepsO hides constants and smaller terms7n + 42 = O(n)
Same class, same speedconstants and memory access still differStrassen's n2.81 method loses to the n³ method on small matrices
Amortized is averageamortized bounds the total of any sequencea doubling array: n appends copy fewer than 2n items in total
Only time countsspace has its own boundmerge sort needs O(n) extra; heapsort O(1)
One size variablekeep every size that mattersbreadth-first search is O(V + E)
Depth is timedepth bounds the stack, not the worknaive Fibonacci: depth n, calls growing about 1.618 times per step
A true bound is a good boundgive the tightest bound you can proveinsertion 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).

An algorithm takes Θ(n) time in its best case and Θ(n²) in its worst case. Is its running time Θ(n²)?

Chapter 9

The Field Guide

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.

The five notations

NotationDefinitionLike 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 ∞>

The numbers

WhatNumberWhy it matters
100n against 2n²crossover at n = 50; B is 20,000 times slower at 106constants 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 ≤ 2c must exceed the leading coefficient
2n² + 3n = Ω(n²)largest c with n0 = 1 is 2a floor cannot pass the limit
n²/2 − 3n = Θ(n²)c1 = 1/4, c2 = 1/2, n0 = 12CLRS's sandwich
1 second at 108 stepsn²: 10,000; n³: 464; 2ⁿ: 26; n!: 11the cliff at the exponential
All pairs, n = 1,000499,500 checksn(n − 1)/2
Binary search, n = 10620 probes⌊log₂n⌋ + 1

Before you state a bound

  1. Name n, or every size variable (V and E for a graph).
  2. Name the case: best, worst, average or amortized.
  3. Count the inner line: multiply nested loops, keep the largest of sequential blocks.
  4. Check library calls for hidden loops: string building, list membership, slicing.
  5. Give Θ if you can prove both sides; otherwise O, and say so.
  6. Check the size limit against the budget table before you build.

The core code

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

Growth in ML systems

OperationCostWhat it means
Self-attention, length n, width dO(n²d) timetwice the context, four times the attention work
FlashAttention (Dao et al., 2022)O(n²d) time, O(n) extra memorysame time class; it never stores the n × n score matrix
One new token with a KV cacheO(nd) per layerattend over n stored keys; no recompute of old tokens
Embedding lookupO(d) per tokenan array index into a V × d table; the vocabulary size V does not matter
Adam update, p parametersO(p) time, 2p extra memorytwo running averages per parameter

Keep going

The takeaway. Ask how the cost grows, not how big it is today. Then check where the crossover sits against the sizes you run in production.
You propose an O(n log n) design. A colleague offers an O(n) one. What do you check before you switch?

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.

Source

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.

CLRS Chapter 3 · Growth of Functions
Next: Divide and Conquer · Back to Gleams