Sub topic 11
Early Exits: Best and Worst Cases
This chapter assumes you can count the iterations of a single loop and reduce an exact count to Big-O or Big-Theta, as covered in earlier chapters. Every loop so far ran a fixed number of times once you knew n. A loop that can return or break early is different. Its count depends on what the data holds, as well as on how much data there is.
One Size, Many Counts
Linear search scans a list until it finds the target:
def linear_search(items, target):
steps = 0
for x in items:
steps += 1
if x == target:
return True, steps
return False, steps
data = list(range(100))
print(linear_search(data, 0)) # (True, 1) best case
print(linear_search(data, -1)) # (False, 100) worst caseBoth calls use a list of length 100, but one takes 1 step and the other takes 100. "How many steps does linear search take on n items?" has no single answer. You have to say which input of size n you mean.
Defining the Cases
Fix the input size n, then look at every possible input of that size.
| Case | Meaning | Linear search on n items |
|---|---|---|
| Best case | Fewest steps over all inputs of size n | 1 (target is first) |
| Worst case | Most steps over all inputs of size n | n (target last or absent) |
| Average case | Expected steps under a stated input distribution | (n + 1) / 2 if the target is equally likely at each position |
Each case is its own function of n, and each gets its own order of growth. Linear search is Θ(1) in the best case and Θ(n) in the worst case. You can also say linear search is O(n) overall, because no input takes more than n steps. "Linear search is Θ(n)" with no case named is wrong, because the best case does not grow with n.
The average-case figure comes from a sum. If the target sits at position k (counting from 1), the search takes k steps. Averaging over n equally likely positions gives (1 + 2 + ... + n) / n = (n + 1) / 2, which is still Θ(n). You can check it directly:
def linear_search(items, target):
steps = 0
for x in items:
steps += 1
if x == target:
return True, steps
return False, steps
n = 100
data = list(range(n))
total = sum(linear_search(data, t)[1] for t in data)
print(total / n) # 50.5, which is (100 + 1) / 2How to Find Each Case
- Find every exit point:
return,break, or awhilecondition that depends on the data. - For the best case, build the input that reaches an exit as soon as possible.
- For the worst case, build the input that avoids every exit until the loop bound runs out.
- Count iterations for each input, multiply by the work per iteration, and reduce to an order of growth.
Worst case is the usual default. It is a guarantee: no input of size n can do worse. The best case says little on its own, because a well-chosen input makes almost any algorithm look fast.
Early Exits in Nested Loops
An early exit inside nested loops can cut off the whole structure. This function looks for any duplicate:
def has_duplicate(items):
n = len(items)
for i in range(n):
for j in range(i + 1, n):
if items[i] == items[j]:
return True
return False
print(has_duplicate([7, 7, 1, 2])) # True after 1 comparison
print(has_duplicate([1, 2, 3, 4])) # False after 6 comparisonsIn the best case, the first two items match, so the function makes 1 comparison and runs in Θ(1). In the worst case, all items are distinct, every pair is compared, and the count is n(n − 1)/2, which is Θ(n²).
Exercise
The function below returns whether a list is in non-decreasing order. For a list of length n >= 2, give the number of comparisons in the best and worst case, and their orders of growth. def is_sorted(items): for i in range(len(items) - 1): if items[i] > items[i + 1]: return False return True
Show answer
Best case: 1 comparison, when the first pair is out of order, so Θ(1). Worst case: n - 1 comparisons, when the list is sorted or only the last pair is out of order, so Θ(n).
Exercise
A colleague says "has_duplicate is O(n^2), so it is slow on every input." What is wrong with this claim?
Show answer
O(n^2) is an upper bound, and it is reached only in the worst case, when all items are distinct. When a duplicate appears early, the function stops after a few comparisons. The best case is Θ(1), so the function is not slow on every input.