Sub topic 12
Big-O, Omega, and Theta in brief
This chapter assumes you can read a running-time function such as T(n) = 3n + 2 and that you know best, worst, and average case. Asymptotic notation describes how a function grows as n gets large. It ignores constant factors and small terms.
The three symbols
Let T(n) be a running-time function, for example the number of comparisons an algorithm makes on inputs of size n. Let g(n) be a simple comparison function such as n or n².
| Notation | Meaning | Informal reading |
|---|---|---|
| T(n) = O(g(n)) | T(n) ≤ c·g(n) for all n ≥ n₀ | g is an upper bound |
| T(n) = Ω(g(n)) | T(n) ≥ c·g(n) for all n ≥ n₀ | g is a lower bound |
| T(n) = Θ(g(n)) | Both of the above hold, with different constants | g is a tight bound |
Here c and n₀ are positive constants you choose. Θ means T grows at the same rate as g.
Checking a bound with constants
Take T(n) = 3n + 2. For n ≥ 2 we have 3n ≤ 3n + 2 ≤ 4n. So the constants c₁ = 3, c₂ = 4, and n₀ = 2 show that T(n) = Θ(n). The script below checks this over a range of n. A finite check is not a proof, but it catches wrong constants.
def T(n):
return 3 * n + 2
c1, c2, n0 = 3, 4, 2
print(all(c1 * n <= T(n) <= c2 * n for n in range(n0, 1000))) # TrueApplying the notation to a case
Each case has its own running-time function. Insertion sort makes these comparison counts:
- Best case (sorted input): n − 1 comparisons, which is Θ(n).
- Worst case (reversed input): n(n − 1)/2 comparisons, which is Θ(n²).
The notation describes one function at a time. You first choose a case, which gives you a function. Then you choose a bound for that function.
Common errors
- Dropping the case. "Insertion sort is O(n²)" is true, because the worst case never exceeds n². It says nothing about the best case, which is Θ(n).
- Treating O as "worst case". O is an upper bound on a function. You can state it for the best case, average case, or worst case.
- Treating Θ as "average case". Θ means the upper and lower bounds match. Any case function can have a Θ bound if one exists.
- Reading constants as irrelevant. Notation hides them. An algorithm that takes 100n steps and one that takes n² steps compare differently for small n, even though the first is Θ(n) and the second is Θ(n²).
Exercise
Linear search on n items makes between 1 and n comparisons. Give a Θ bound for its best case, its worst case, and its average case when the target is equally likely at any position. Then say whether "linear search is O(n)" is correct.
Show answer
Best case: 1 comparison, which is Θ(1). Worst case: n comparisons, which is Θ(n). Average case: (n + 1)/2 comparisons, which is Θ(n). The statement "linear search is O(n)" is correct, because n is an upper bound on every case. It does not describe the best case tightly, since that case is Θ(1).