Sub topic 8
Best, Worst, and Average Case
This chapter assumes you can read the Big O definition and simplification rules from earlier chapters. It also assumes you can derive the complexity of simple loops. Here you will learn why one algorithm can have several running times for the same input size, and how to state each one correctly.
Same size, different cost
Big O describes cost as a function of input size n. Many algorithms do not take the same number of steps for every input of size n. The contents and order of the data also matter.
Take a linear search:
def linear_search(items, target):
for i, x in enumerate(items):
if x == target:
return i
return -1For a list of 1,000 items, the cost depends on where the target is:
- If the target is the first item, the loop does one comparison.
- If the target is the last item or absent, the loop does 1,000 comparisons.
So "the running time of linear search" is not one function of n. It is a family of functions, one per input. To get a single function, we pick one input of each size and measure it. The three standard choices are the best, worst, and average case.
The three cases
- Best case: the input of size n that makes the algorithm do the least work.
- Worst case: the input of size n that makes it do the most work.
- Average case: the expected work over all inputs of size n, under a stated probability distribution.
For linear search on n items:
| Case | Input | Comparisons | Big O |
|---|---|---|---|
| Best | Target is first | 1 | O(1) |
| Worst | Target is last or absent | n | O(n) |
| Average | Target equally likely at any position | (n + 1) / 2 | O(n) |
The average comes from summing the cost of each position and dividing by the number of positions: (1 + 2 + ... + n) / n = (n + 1) / 2. The constant 1/2 and the lower-order term disappear when you simplify, so the average case is still O(n).
Cases are not the same as bounds
This is the most common mistake in this topic. Best, worst, and average describe which input you analyze. O, Omega, and Theta describe what kind of bound you put on a cost function. The two ideas are independent.
Each case produces its own function, and any of the three bounds can describe that function:
- The worst case of linear search is exactly n comparisons. That function is O(n), Omega(n), and Theta(n).
- The best case is 1 comparison. That function is O(1) and Theta(1).
Two statements that sound similar mean different things:
- "Linear search is O(n)" usually means its worst case is bounded above by n. It is also true of every case, because no input costs more than about n.
- "Linear search is Omega(1)" says no input costs less than a constant. It is true but tells you almost nothing.
A callout is worth keeping in mind here.
Worst case: the guarantee
The worst case is the default in most analysis, for three reasons:
- It is a guarantee. If the worst case is O(n log n), no input will be slower, up to constants.
- It needs no assumptions about the data.
- For many algorithms, the worst case occurs often. Searching for a missing key is the normal outcome in many programs.
Use the worst case when a slow response is a failure, such as in real-time systems, request handlers with timeouts, or code that handles input from untrusted users. An attacker can deliberately send the worst-case input.
Best case: usually the least useful
The best case tells you the floor, but the floor rarely matches real workloads. Its main use is spotting early exits. In the has_duplicate function from the first chapter, the best case is O(1) when the first two items are equal. The worst case is O(n^2) when there are no duplicates. A best case that is much faster than the worst case is a sign that input structure matters, and it is worth asking how likely each input is.
A best case can also be useful when the input is usually close to it. Insertion sort is the classic example.
Average case: needs a distribution
An average is only meaningful once you state what you are averaging over. For linear search we assumed the target is equally likely at each position and always present. If the target is absent 90% of the time, the average cost moves close to n. The big O stays O(n), but the constant changes.
Average-case analysis has two steps:
- Choose a probability distribution over inputs of size n. The usual default is "all permutations equally likely".
- Compute the expected cost: the sum of cost times probability over all inputs.
The distribution is an assumption, not a fact. If real data follows a different distribution, the average-case result may not hold.
Worked example: insertion sort
Insertion sort shows all three cases with very different results. The function below counts comparisons so you can see the cost directly.
import random
def insertion_sort_comparisons(items):
a = list(items)
comparisons = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comparisons += 1
if a[j] > key:
a[j + 1] = a[j]
j -= 1
else:
break
a[j + 1] = key
return comparisons
n = 1000
sorted_input = list(range(n))
reversed_input = list(range(n, 0, -1))
random.seed(0)
random_input = random.sample(range(n), n)
print("best (sorted): ", insertion_sort_comparisons(sorted_input))
print("worst (reversed):", insertion_sort_comparisons(reversed_input))
print("random: ", insertion_sort_comparisons(random_input))The first two lines print exactly 999 and 499500. The random count is not fixed by the code, but it lands near 250,000, about a quarter of n squared.
The reasoning behind those numbers:
- Best case, sorted input. Each new item is compared once and stays in place. That is n - 1 comparisons, so O(n).
- Worst case, reverse-sorted input. Item i is compared with all i items before it. The total is 1 + 2 + ... + (n - 1) = n(n - 1)/2, so O(n^2).
- Average case, random input. On average, an item moves past about half of the items before it. The total is roughly n^2/4 comparisons. The constant is smaller than the worst case, but the growth is still O(n^2).
So insertion sort is Theta(n) in its best case and Theta(n^2) in its worst and average cases. It has no single Theta for "the algorithm" as a whole, which is why the case must be named.
When the cases differ: common algorithms
| Algorithm | Best | Average | Worst | Worst-case trigger |
|---|---|---|---|---|
| Linear search | O(1) | O(n) | O(n) | Target last or absent |
| Binary search | O(1) | O(log n) | O(log n) | Target absent or found at the last step |
| Insertion sort | O(n) | O(n^2) | O(n^2) | Reverse-sorted input |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | None, the split is always even |
| Quicksort (first-item pivot) | O(n log n) | O(n log n) | O(n^2) | Already sorted input |
| Hash table lookup | O(1) | O(1) | O(n) | Many keys collide in one bucket |
Quicksort and hash tables show why you must read the case carefully. Both are fast on typical data, but their worst cases are much slower. Real implementations reduce the risk with randomized pivots or randomized hash seeds, which makes the worst case very unlikely without removing it.
Merge sort is the opposite. Its cost barely depends on input order, so all three cases agree. That predictability is a reason to choose it when guarantees matter.
Randomized algorithms: a different kind of average
A randomized algorithm makes random choices itself, such as picking a random pivot. Its expected running time is an average over its own coin flips, not over the input. For a fixed input, the expected cost of randomized quicksort is O(n log n). This is a stronger statement than the usual average case, because it holds for every input and needs no assumption about the data.
Common errors
- Equating cases with bounds. Saying "best case is Omega" or "worst case is O" as if they were definitions. Name the case, then the bound.
- Quoting the average without a distribution. If you cannot say what you averaged over, the number has no meaning.
- Reporting only the best case. "Insertion sort is O(n)" is true only for nearly sorted input.
- Assuming worst case is always the realistic case. For quicksort and hash tables, the worst case is rare, and the average describes typical behavior better.
- Mixing up average case and amortized cost. Average case averages over different inputs. Amortized cost averages over a sequence of operations on one data structure, with no probability involved. The next chapters cover amortized analysis.
Exercise
A function scans a list of n distinct integers for the maximum value, but returns immediately if it sees the value 0. Give the best-case and worst-case time complexity, and say what input produces each.
Show answer
Best case is O(1): the first item is 0, so the function returns after one comparison. Worst case is O(n): the list contains no 0 (or 0 is the last item), so every item is examined. The average case depends on how likely 0 is and where it appears, so it cannot be stated without assuming a distribution.
Exercise
A teammate says "quicksort is O(n log n) in the average case, so its worst case must be Omega(n log n) and its best case must be O(n)." Which parts of this claim are wrong, and why?
Show answer
The claim confuses cases with bounds. Quicksort's average case being O(n log n) says nothing that forces the worst case to be Omega(n log n) as a deduction, and in fact the worst case (with a bad pivot rule) is Theta(n^2), which is also Omega(n log n) but for a different reason. The best case of quicksort is still Theta(n log n), not O(n), because even with perfect splits it must partition at every level. Each case must be analyzed on its own input, and each can then be given O, Omega, or Theta bounds.