Big-O Notation & Running Time
Counting steps, comparing growth rates, and knowing what fits in a second.
is . That is true, and strange: the exponential overtakes the polynomial only once passes about 117,000. Asymptotic notation is exact about what happens eventually and silent about when, and using it well means knowing both. This lesson makes the notation precise, turns loops into sums, and turns a problem's constraints into the running time you must hit.
What you’ll learn
- State the definitions of , , , and , and prove bounds with explicit constants and .
- Keep two axes apart: which cost function (worst, best, average, expected, amortized) and which bound (, , ).
- Count the steps of nested, dependent, halving, harmonic and doubling loops with sums.
- Measure input size correctly, in bits for numbers, and account for space as well as time.
- Estimate the complexity of a code snippet and match it against a problem's constraints.
O, Ω and Θ, exactly
A running time is a function from input sizes to step counts, and asymptotic notation compares such functions while ignoring two things on purpose: constant factors, and small inputs. Throughout, and are nonnegative functions of .
An upper bound, with generous constants. For , and :
The same bound, with a tighter constant. exactly when , which first holds at () and then for every larger :
A lower bound. Every term is nonnegative, so
It is not . If held for all , dividing by would give for all large , which no constant satisfies:
The constants are not unique, and they are not the point: the definition asks only that some pair works. Three reading rules prevent most mistakes:
- The "=" is a one-way membership claim. is true, because an upper bound need not be tight, but "" means nothing. Say when you mean a tight bound.
- Limits settle most comparisons. If with , then ; if , then ; if , then . The converse fails: , although its ratio to oscillates forever.
- The base of a logarithm is a constant factor, , so needs no base. In an exponent, constants are not harmless: is not .
Which of these statements is true?
Show the answer
C.
: every exponential with base above 1 eventually outgrows every polynomial. "Eventually" is doing heavy lifting here: is the larger one for every from 2 to 117,308, and takes over only from on.
Which running time? Worst, best, average
An algorithm has one running time per input, not per input size. To get a function of you must say how the inputs of size are combined, and that choice is a separate axis from , and .
| Cost function | Defined as | Insertion sort, distinct keys (comparisons) |
|---|---|---|
| Worst case | the maximum over inputs of size | , on reversed input |
| Best case | the minimum over inputs of size | , on sorted input |
| Average case | the mean over a distribution of inputs | , over random orders |
| Expected | for each input, the mean over the algorithm's own random choices; then the worst input | not randomized |
| Amortized | the worst total over sequences of operations, divided by their number | not a sequence of operations |
Now combine the two axes. "Insertion sort is " is true of every input. "Insertion sort is " is false as a claim about every input: on sorted input it makes comparisons. The precise statements are "its worst-case running time is " and "its best-case running time is ".
A lower bound on the worst case, such as "worst case ", says that some inputs of each large size are that slow, not that all of them are.
Think first Quicksort with a uniformly random pivot makes about comparisons on average, for every input. Is that an average-case bound?
No, it is an expected bound. The average is over the algorithm's own coin flips, and it holds for each fixed input, sorted and adversarial ones included. An average-case bound averages over inputs drawn from a distribution, and says nothing about the inputs that distribution rarely produces. The exact expectation is comparisons.
Counting loops
The running time of a loop is the sum, over its iterations, of the work done in each. So analysis turns code into sums, and sums into closed forms. Five shapes cover most of what you will meet:
def count_ops(n):
ops = [0] * 5
for i in range(n): # 1. independent nested loops
for j in range(n):
ops[0] += 1
for i in range(n): # 2. dependent: j < i
for j in range(i):
ops[1] += 1
k = n # 3. halving
while k > 1:
k //= 2
ops[2] += 1
for d in range(1, n + 1): # 4. the multiples of d up to n
for m in range(d, n + 1, d):
ops[3] += 1
i = 1 # 5. doubling outer, inner up to i
while i <= n:
for j in range(i):
ops[4] += 1
i *= 2
return ops
print(count_ops(1000)) # [1000000, 499500, 9, 7069, 1023]Loop 4 is the shape of "for every , visit its multiples", as in listing the divisors of every number up to . Loop 5 is the shape of anything built by doubling.
Independent loops multiply:
Dependent loops give an arithmetic series: half of loop 1, and still quadratic.
Halving reaches 1 after rounds, because after rounds :
Harmonic loops: the inner loop runs times, with , and :
Geometric loops: when the work doubles every round, the last round dominates.
Loop 4 runs its body times for each . For , about how many times does it run in total? (Loop 1 runs a million times.)
Show the answer
7069
Exactly , between and . Two nested loops, yet : the inner loop shrinks like . Counting how deeply loops are nested is not enough; count the iterations.
Growth rates, constants and the time limit
For constants , and , every power of a logarithm is , every polynomial is , and every exponential is . Limits of ratios, with l'Hôpital's rule where needed, prove each link of the chain:
Asymptotics speak only about large . For small inputs the constants decide: an algorithm that costs steps loses to one that costs until . That is why library sorts finish small subarrays with insertion sort.
Contest and interview problems state and a time limit, usually 1–2 seconds. With the rule of thumb of about simple operations per second in a compiled language, the two together are a complexity budget:
| up to about | Budget | Typical algorithms |
|---|---|---|
| 10–11 | all permutations | |
| 20–25 | all subsets, bitmask DP | |
| 40 | meet in the middle | |
| 500 | Floyd–Warshall, interval DP | |
| 5,000 | all pairs, quadratic DP | |
| sorting, heaps, binary search, segment trees | ||
| one pass, two pointers, prefix sums | ||
| larger | or | fast exponentiation, binary search on the answer, a formula |
Space, and the size of a number
Space complexity counts memory the way time complexity counts steps, and usually what matters is the auxiliary space, the memory beyond the input itself: merge sort needs extra cells, heapsort . Recursion costs space as well, one stack frame per pending call. Quicksort's recursion can be calls deep, unless it recurses into the smaller part and loops on the larger, which caps the depth at .
Both are measured against the input size in bits. For most problems that is the number of items, up to the size of a word. When the input is a single number , though, the input is the bits that write it down, and that changes everything:
def is_prime(N): # trial division: about sqrt(N) divisions
if N < 2:
return False
d = 2
while d * d <= N:
if N % d == 0:
return False
d += 1
return TrueFor the prime the loop makes 46,339 divisions; for the prime , about . Every 2 extra bits double the work: is polynomial in the value but exponential in the length.
Algorithms that are polynomial in the numeric values of the input but not in its length are called pseudo-polynomial. The table for the knapsack problem is the famous one, and the Dynamic Programming topic returns to it. Primality itself can be decided in time polynomial in (Agrawal, Kayal & Saxena, 2002), and in practice software uses the randomized Miller–Rabin test.
Think first A loop runs times on the input number . Is that linear time?
It is linear in the value , but the input has only bits, so steps is exponential in the input size. Summing with a loop takes exponential time; the formula takes a few multiplications of -bit numbers, which is polynomial.
Recognizing it
Two skills make up this lesson's "recognize it": reading code to get its complexity, and reading constraints to get the complexity you need. For code, find what each loop variable does (counts up by one, halves, doubles, or only moves forward) and sum the iterations. Watch for the two classic illusions: nested loops that are linear, and single loops that are quadratic.
| Code shape | Iterations | Complexity |
|---|---|---|
for i in range(n): for j in range(i + 1, n): | pairs | |
while lo < hi: halving the range [lo, hi) | about | |
i = 1; while i < n: i *= 3 | ||
for d in range(1, n + 1): for m in range(d, n + 1, d): | about | |
j = 0, then for i in range(n): while j < n and ok(i, j): j += 1 | at most : j never moves back | , though nested |
for x in queries: if x in lst: with a list of items | , hidden in in | , though single |
j is shared by all values of i and only moves forward, so the inner loop runs at most times in total: the two-pointer pattern. And in on a list scans it, so one innocent line hides a loop; a set makes each test expected.Common mistakes
- Counting loops instead of iterations: nested does not mean quadratic, and a single loop does not mean linear.
- Forgetting hidden costs:
list.pop(0),list.insert(0, x),x in list, slicing, string concatenation in a loop, and arithmetic on huge integers all cost more than one step. - Treating expected bounds as worst case: a hash map is per operation in expectation, and adversarial keys can make it linear.
- Using the value of a number as its size, so that a loop up to looks linear.
- Ignoring space: an table for has cells, far beyond any memory limit.
Which of these runs in time in total?
for i in range(n): for j in range(i): ...- A pointer
jstarts at 0 and, insidefor i in range(n), only ever moves forward, at most up ton for i in range(n): if a[i] in b: ..., wherebis a list of itemsfor i in range(1, n): k = i; while k > 1: k //= 2
Show the answer
B. A pointer j starts at 0 and, inside for i in range(n), only ever moves forward, at most up to n
The shared pointer moves forward at most times over the whole run, and the outer loop runs times, so the total is at most steps, whatever the nesting looks like. This is the two-pointer pattern; the Optimized lesson Amortized Analysis makes the "total, not per iteration" argument formal.
Key takeaways
- , , mean , , or both, for all ; and are the strict versions, and the limit of settles most comparisons.
- Worst, best, average, expected and amortized cost form a separate axis from , , : always say which cost function a bound is about.
- Turn loops into sums: dependent loops give , halving gives , harmonic loops , doubling loops . Count iterations, not nesting.
- Measure input size in bits: an loop over a number is exponential in its bits, and knapsack is pseudo-polynomial.
- At about simple operations per second, constraints become a budget: about for and for ; constants, caches and hidden costs decide the rest.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which is the most precise true statement about ?
Show the answer
C.
The term dominates, since . So , which says both and . The bound is true but loose.
How many times does i = 1; while i < n: i *= 3 run its body?
- About
- , which is
- About
- Three times
Show the answer
B. , which is
After rounds , and the loop stops at the first with : , which is 7 for and 13 for . The base only changes a constant factor: .
An algorithm's worst-case running time is . What follows?
- Every input of size takes about steps
- Its average-case running time is
- Its best-case running time is
- No input of size takes more than steps, and for every large some input takes at least
Show the answer
D. No input of size takes more than steps, and for every large some input takes at least
A bound on the maximum over inputs bounds every input from above, and says that the maximum itself grows like . It says nothing about typical or easy inputs: insertion sort's worst case is and its best case .
What is the total running time of i = 1; while i <= n: (do i steps of work); i *= 2?
- : about rounds of up to work
Show the answer
B.
The work is : a geometric series is dominated by its last term. Bounding every round by the largest one overestimates by a log factor.
Trial division tests whether is prime with arithmetic operations. Why is it not a polynomial-time algorithm?
- Because is not a polynomial
- Because division is slower than addition
- Because the input is the bits of , and is exponential in
- It is polynomial: beats
Show the answer
C. Because the input is the bits of , and is exponential in
Complexity is measured against the length of the input. A 61-bit number needs over a billion trial divisions, and every 2 extra bits double that. Polynomial-time primality tests run in time polynomial in .
Go deeper
- Models of Computation · RAM, word RAM and cell probe: what one “step” really costs.
- Lower Bounds by Adversary Arguments · Proving no algorithm can do better: maximum and minimum, the second largest, and information.
- Beyond Worst-Case Analysis · Average-case, smoothed and instance-optimal analysis of algorithms.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 3, "Characterizing Running Times".
- D. E. Knuth, "Big Omicron and Big Omega and Big Theta," ACM SIGACT News 8(2) (1976), 18–24.
- R. L. Graham, D. E. Knuth & O. Patashnik, Concrete Mathematics, 2nd ed. (Addison-Wesley, 1994), chapters 2, "Sums", and 9, "Asymptotics".
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), §1.4, "Analysis of Algorithms".