O, Omega and Theta
Counting steps exactly gives a worst case as a polynomial with awkward coefficients, something like . Exact counts are useful, but they carry detail nobody needs when comparing algorithms: the constant in front depends on what you call a step, and the lower-order terms vanish next to the leading one once is large. Asymptotic notation throws that detail away on purpose and keeps the growth rate. This lesson treats the three workhorses, , and , as tools for proofs: how to pick the constants, how to show a bound is false, which algebraic rules hold, and what a formula like actually means.
The definitions and a first set of rules are in Asymptotic Notation in the Discrete Mathematics course. Here they are applied to running times.
Functions we compare
A running time is defined for whole numbers and is never negative. The notation below is stated for functions that are asymptotically nonnegative: for all large enough . Every running time qualifies, and so does something like , which is negative only for small .
O: an upper bound
is a set of functions, those that eventually bounds from above, up to a constant factor. To prove you exhibit two numbers, and , called the witnesses, and show the inequality for every .
Example. Take and . There are many valid pairs of witnesses:
- , : for , and , so . This is the lazy choice: bound every term by the leading power.
- , : is the same as , which holds from on () and fails at ().
A smaller forces a larger , and never works, because for every . The program finds the smallest for several choices of by checking every up to 10,000. A check over a finite range is not a proof, but here is a quadratic with positive leading coefficient once , so once it turns non-negative it stays so.
def f(n):
return 4 * n * n + 25 * n + 6
def smallest_n0(c, limit=10_000):
last_bad = None
for n in range(1, limit + 1):
if f(n) > c * n * n:
last_bad = n
if last_bad == limit:
return None
return 1 if last_bad is None else last_bad + 1
for c in [4, 4.5, 5, 6, 10, 35]:
n0 = smallest_n0(c)
print(f"c = {c:>4}: " + ("no n0 up to 10000" if n0 is None else f"smallest n0 = {n0}"))c = 4: no n0 up to 10000
c = 4.5: smallest n0 = 51
c = 5: smallest n0 = 26
c = 6: smallest n0 = 13
c = 10: smallest n0 = 5
c = 35: smallest n0 = 1
Omega: a lower bound
The same is in with and , since the extra terms are positive. Lower bounds are usually the easy direction for a sum of positive terms (drop all but one) and the hard direction for a difference: needs , which holds once .
Theta: both at once
says that is an asymptotically tight bound: is sandwiched between two constant multiples of . The connection with the other two is exact.
Theorem. if and only if and .
One direction is immediate: the sandwich contains both inequalities. For the other, if the bound holds from with constant and the bound from with constant , both hold from . So , with , , .
Showing that a bound is false
To show you must defeat every pair of witnesses. The standard argument is by contradiction.
Claim. . Suppose for all . Dividing by gives for all , which fails at . No constant can cap a quantity that grows without bound.
The same pattern shows (take ) but : the ratio is unbounded. A constant in the exponent is not a constant factor.
Rules you can use without re-proving them
Write for each kind of bound. The following hold for all asymptotically positive , , :
| Property | Statement |
|---|---|
| Transitivity | and imply ; the same for and |
| Reflexivity | , , |
| Symmetry | if and only if |
| Transpose symmetry | if and only if |
| Constant factors | for every constant |
| Sums |
Transitivity multiplies the constants: from (for ) and (for ) you get for . Transpose symmetry divides by the constant: is the same as . These rules make behave like equality and , like and , with one big difference: not every pair of functions is comparable. The next lesson, Little o, Little omega and Limits, shows an example.
Notation inside formulas
The equals sign in means "is a member of". It is a one-way equals: is true, and writing it backwards, , says nothing.
When asymptotic notation appears inside a larger formula, it stands for an anonymous function from that set. For example
means for some function in that we don't care to name, such as the cost of merging. A chain like is read left to right: whatever anonymous functions are chosen on the left, the right side can be made true. Each step may lose information and never gains any.
A classic trap. Here is a wrong "proof" that is , by induction. Base: . Step: if , then . The error is that is not a statement about a single . A proof of must use the same constant for every , and the step quietly raises the constant by one each time. Written with an explicit constant, the induction step would need , that is , which fails. The ratio grows without bound:
for n in [10, 100, 1000, 10000]:
s = n * (n + 1) // 2
print(f"n = {n:>5}: S(n) = {s:>9}, S(n)/n = {s / n:8.1f}, S(n)/n^2 = {s / n**2:.4f}")n = 10: S(n) = 55, S(n)/n = 5.5, S(n)/n^2 = 0.5500
n = 100: S(n) = 5050, S(n)/n = 50.5, S(n)/n^2 = 0.5050
n = 1000: S(n) = 500500, S(n)/n = 500.5, S(n)/n^2 = 0.5005
n = 10000: S(n) = 50005000, S(n)/n = 5000.5, S(n)/n^2 = 0.5000
The last column settles near , so .
O versus Theta for running times
The difference between and matters when you describe an algorithm with a single phrase. Insertion sort's worst case is (reversed input) and its best case is (sorted input, see Counting Steps Exactly). Therefore:
- "The running time of insertion sort is " is true: every input of size costs at most .
- "The running time of insertion sort is " is true: every input costs at least a pass over the array.
- "The running time of insertion sort is " is false as a statement about every input: a sorted array runs in linear time. It is true of the worst-case running time.
The program counts the shifts (executions of the inner loop body) on three kinds of input and divides by .
import random
def shifts(a):
a = list(a)
count = 0
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
count += 1
a[j + 1] = key
return count
rng = random.Random(7)
print(f"{'n':>5} {'sorted':>8} {'random':>8} {'reversed':>9} random/n^2 reversed/n^2")
for n in [100, 200, 400, 800]:
up = list(range(n))
mixed = up[:]
rng.shuffle(mixed)
s, r, w = shifts(up), shifts(mixed), shifts(up[::-1])
print(f"{n:>5} {s:>8} {r:>8} {w:>9} {r / n**2:10.3f} {w / n**2:12.3f}") n sorted random reversed random/n^2 reversed/n^2
100 0 2629 4950 0.263 0.495
200 0 10604 19900 0.265 0.497
400 0 37260 79800 0.233 0.499
800 0 158269 319600 0.247 0.499
Sorted input needs no shifts, reversed input needs exactly , and a random order lands near . One covers all three columns; no single does.
Test yourself
Which pair of witnesses proves ?
- ,
- ,
- ,
- ,
Why is ?
- Because is negative for some
- Because the ratio is unbounded, so no constant works
- Because the base is the same
- It is: take
In , what does stand for?
- The set of all linear functions, added to
- Some unnamed function that is in
- Exactly
- An upper bound only
Which statement about insertion sort is false?
- Its running time is
- Its running time is
- Its worst-case running time is
- Its running time on every input is