Growth Rates and Big-O
Some formulas grow slowly and some explode. When a program handles items, the number of steps it takes might grow like , , , or , and for large that difference decides whether it finishes in a millisecond or never. This lesson compares these growth rates with tables, counts the steps of real loops, and introduces Big-O notation, the shorthand programmers use for them.
The usual suspects
These are the functions that come up again and again. is the logarithm base 2: how many times you can halve before reaching 1.
| Name | Formula | Doubling does this to the work |
|---|---|---|
| constant | nothing | |
| logarithmic | adds 1 step | |
| linear | doubles it | |
| linearithmic | slightly more than doubles it | |
| quadratic | multiplies it by 4 | |
| exponential | squares it |
A table makes the difference concrete:
import math
print(f"{'n':>6} {'log2 n':>7} {'n log2 n':>10} {'n²':>12} {'2ⁿ':>24}")
for n in [1, 10, 20, 50, 100, 1000]:
two_n = f"{2**n:.3e}" if n > 60 else f"{2**n:,}"
print(f"{n:>6} {math.log2(n):>7.2f} {n * math.log2(n):>10.0f} {n*n:>12,} {two_n:>24}") n log2 n n log2 n n² 2ⁿ
1 0.00 0 1 2
10 3.32 33 100 1,024
20 4.32 86 400 1,048,576
50 5.64 282 2,500 1,125,899,906,842,624
100 6.64 664 10,000 1.268e+30
1000 9.97 9966 1,000,000 1.072e+301
At a billion simple steps per second, for takes 10 seconds. for would take about years, thousands of times the age of the universe. of a billion is only about 30.
Counting the steps of code
The growth rate comes from the shape of the code, not the speed of the machine:
- one loop over items → about steps
- a loop inside a loop, both over → about steps
- halving the problem each step (binary search) → about steps
- trying every subset of items → steps
def linear(n):
steps = 0
for i in range(n):
steps += 1
return steps
def all_pairs(n):
steps = 0
for i in range(n):
for j in range(n):
steps += 1
return steps
def halving(n):
steps = 0
while n > 1:
n //= 2
steps += 1
return steps
for n in [8, 16, 32, 64]:
print(f"n={n:>3} linear={linear(n):>3} pairs={all_pairs(n):>5} halving={halving(n)}")n= 8 linear= 8 pairs= 64 halving=3
n= 16 linear= 16 pairs= 256 halving=4
n= 32 linear= 32 pairs= 1024 halving=5
n= 64 linear= 64 pairs= 4096 halving=6
Each time doubles, the linear count doubles, the pair count quadruples, and the halving count goes up by just one.
Big-O: keep only the fastest-growing term
Suppose a function takes exactly steps. For small the 500 dominates. But as grows, the term takes over and the rest becomes noise:
Big-O notation keeps only the dominant term and drops its constant factor: is . It describes how the cost grows, not its exact size. Two common rules:
- drop constant factors: and are both
- drop smaller terms: is
The ranking, slowest-growing first: .
A picture shows how quickly the curves separate (the y-axis is cut off at 400):
import numpy as np
import matplotlib.pyplot as plt
n = np.linspace(1, 20, 200)
plt.figure(figsize=(6, 4))
for y, label in [(np.log2(n), "log₂ n"), (n, "n"), (n * np.log2(n), "n log₂ n"),
(n**2, "n²"), (2**n, "2ⁿ")]:
plt.plot(n, y, label=label)
plt.ylim(0, 400)
plt.xlabel("n (input size)")
plt.ylabel("steps")
plt.legend()
plt.title("Growth rates")
print("2^n passes n^2 for good after n =", next(k for k in range(5, 50) if 2**k > k**2) - 1)2^n passes n^2 for good after n = 4
In software
- Searching. Scanning a list is . Binary search on sorted data is : about 30 steps for a billion items. A hash table lookup is on average.
- Sorting. Bubble sort is . Merge sort and Python's built-in
sortedare . For a million items that is about steps instead of . - Nested loops over the same data (comparing every user with every other user) are the classic accidental . They work on test data and time out in production.
- Brute-forcing passwords is exponential in the length, which is why every extra character makes a password far stronger (see Password Policy).
- LLM attention compares every token with every other token, which is in the context length. That is why long contexts are expensive.
The Time Complexity lesson in the DSA course takes this further.
Exercises
Exercise 1: Doubling
An job takes 3 seconds for 10 000 items. Roughly how long for 40 000 items? And for an job that takes 3 seconds for 10 000 items?
Answer
About 48 s for ; about 13.8 s for .
Solution
import math
r = (40000 * math.log2(40000)) / (10000 * math.log2(10000))
print(round(r, 2), round(3 * r, 1))4.6 13.8
Exercise 2: Simplify to Big-O
Write each in Big-O: (a) , (b) , (c) , (d) .
Answer
(a) , (b) , (c) , (d) .
Solution
Keep the fastest-growing term and drop its constant. In (d) any exponential eventually beats any power: for every .
Exercise 3: Count the steps
How many times does steps += 1 run in this code, as a formula in ? What is its Big-O?
for i in range(n):
for j in range(i):
steps += 1Answer
times, which is .
Solution
The inner loop runs times:
def count(n):
steps = 0
for i in range(n):
for j in range(i):
steps += 1
return steps
print([count(n) for n in [4, 10, 100]], [n * (n - 1) // 2 for n in [4, 10, 100]])[6, 45, 4950] [6, 45, 4950]
Exercise 4: When does exponential win?
Algorithm A takes steps and algorithm B takes steps. Find the smallest for which B is slower than A from then on. Use a short Python search.
Answer
(B is slower for every ).
Solution
Compare the two around the crossover:
From there doubles with every step while grows by less than 11%, so B stays slower. The search finds the last where B is still at most as slow as A, and adds 1:
last_fast = max(n for n in range(1, 100) if 2**n <= 1000 * n**2)
n = last_fast + 1
print(n, 2**n, 1000 * n**2)19 524288 361000
Despite its 1000× head start, the quadratic algorithm wins from on.
Test yourself
What is in Big-O notation?
Binary search on 1 million sorted items needs about how many steps?
- 20
- 1 000
- 500 000
- 1 000 000
Doubling the input of an algorithm multiplies its running time by about:
- 2
- 4