Sub topic 11
Early Exits: Best and Worst Cases
Every loop in the earlier chapters ran a fixed number of times once you knew n. A loop over range(n) always ran n times, and a triangular loop always ran n(n-1)/2 times. Real code often stops early. A search returns as soon as it finds its target, and a validity check quits at the first bad value. For these loops, the step count depends on what the input contains as well as on its size.
This chapter assumes you can count single, nested, and dependent loops, and that you can reduce an exact count to Big-O and Big-Theta, as covered in earlier chapters. It shows how to separate one input-dependent count into a best case, a worst case, and an average case, and how to state each one correctly.
Why One Number Is No Longer Enough
Here is the linear search from the Topic Spine. It counts one step per element it examines and returns the moment it finds a match.
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 the same size, n = 100. The first call takes 1 step and the second takes 100. The phrase "the running time for input size n" therefore has no single answer here. Different inputs of size n lead to different counts.
The fix is to fix n and ask about the range of counts across all inputs of that size:
- The best case is the minimum number of steps over all inputs of size
n. - The worst case is the maximum number of steps over all inputs of size
n. - The average case is the expected number of steps when inputs are drawn from a stated probability distribution.
Each of these is a function of n again, so you can reduce each one to an order of growth.
Finding the Best and Worst Inputs
To analyze an early-exit loop, describe the input that triggers the exit as soon as possible and the input that delays it as long as possible. Then count the loop for each.
For linear_search on a list of length n:
| Case | Input that causes it | Steps | Order of growth |
|---|---|---|---|
| Best | Target is the first element | 1 | Θ(1) |
| Worst (found) | Target is the last element | n | Θ(n) |
| Worst (not found) | Target is absent | n | Θ(n) |
| Average (found, uniform position) | Target equally likely at each index | (n + 1) / 2 | Θ(n) |
The worst case shows up twice. A target in the last position and a missing target both make the loop examine every element. An unsuccessful search always costs the full n steps. A loop that only returns early on success has no early exit when the search fails.
Computing the Average Case
The average case needs an assumption about how inputs are distributed. The usual one for search is that the target is present and equally likely to sit at any of the n positions. If the target is at index k, the loop takes k + 1 steps. Averaging over all positions gives the following, using the arithmetic series from earlier:
(1 + 2 + ... + n) / n = (n(n + 1) / 2) / n = (n + 1) / 2
You can check this by running the search once for every possible target and averaging the counts:
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
print((n + 1) / 2) # 50.5On average, a successful search examines about half the list. Half of n is still Θ(n), so early exits do not change the order of growth of the average case here. They cut the constant factor in half.
The distribution matters. If the target is absent half the time, the expected count is 0.5 * (n + 1) / 2 + 0.5 * n, which is about 0.75n. If recently used items tend to sit near the front, the average can be much smaller. Always state the distribution when you give an average-case count. Without it, "average" has no defined meaning.
Stating Results Correctly with Big-O and Big-Theta
Mixing up the case with the bound is one of the most frequent mistakes in loop analysis. Two separate questions are involved:
- Which case are you describing: best, worst, or average?
- Which bound are you giving for that case's count: upper (O), lower (Ω), or tight (Θ)?
For linear search, all of these statements are true:
- The worst-case running time is Θ(n).
- The best-case running time is Θ(1).
- The running time is O(n) for every input, because no input needs more than
nsteps. - The running time is Ω(1) for every input, because every non-empty input needs at least 1 step.
This statement is false: "the running time of linear search is Θ(n)" when it is applied to all inputs. That claim would require every input to take at least a constant times n steps, and the best-case input does not.
Worst-case analysis is the most common in practice because it gives a guarantee. No input of size n can do worse. Best-case analysis is rarely useful alone, since almost any algorithm can be lucky. It is still worth computing, because a large gap between the best and worst cases tells you the input's structure matters a lot.
Early Exits in Nested Loops
Returning from inside a nested loop
An early return inside a nested loop leaves every loop at once. This duplicate check compares each pair once using the triangular loop from earlier chapters:
def has_duplicate(items):
steps = 0
n = len(items)
for i in range(n):
for j in range(i + 1, n):
steps += 1
if items[i] == items[j]:
return True, steps
return False, steps
print(has_duplicate([7, 7, 1, 2, 3])) # (True, 1)
print(has_duplicate([1, 2, 3, 4, 5])) # (False, 10)The best case is a duplicate in the first two positions: 1 step, Θ(1). The worst case is a list with no duplicates: every pair gets compared, giving n(n-1)/2 steps, which is Θ(n²). The gap between the cases is now a factor of about n²/2.
`break` only leaves the innermost loop
A break exits only the loop that directly contains it. The outer loop keeps going, so the best case is usually not constant.
def count_until_negative(rows):
steps = 0
for row in rows:
for x in row:
steps += 1
if x < 0:
break
return steps
grid = [
[1, -1, 5, 5],
[-2, 3, 3, 3],
[4, 4, 4, 4],
]
print(count_until_negative(grid)) # 7Here the first row costs 2 steps, the second costs 1, and the third has no negative value and costs all 4. For r rows of c columns:
- Best case: every row starts with a negative value. Each row costs 1 step, so the total is
r, which is Θ(r). - Worst case: no row contains a negative value. The total is
r * c, which is Θ(rc).
Loops Where the Cases Coincide
Not every loop that reads its input has different cases. Finding the maximum of a list has to look at every element, because any unexamined element could be larger:
def find_max(items):
steps = 0
best = items[0]
for x in items[1:]:
steps += 1
if x > best:
best = x
return best, steps
print(find_max([3, 9, 2, 7])) # (9, 3)
print(find_max([9, 7, 3, 2])) # (9, 3)The loop body always runs n - 1 times. The if changes which statements run inside an iteration, but each of them is a constant-time step, so the count of iterations stays the same. When a function has no early exit and no data-dependent loop bounds, the best, worst, and average cases are all the same function, and a single Θ describes all inputs.
Edge cases also need a look. find_max fails on an empty list because items[0] raises an IndexError. linear_search on an empty list takes 0 steps, which is both its best and worst case for n = 0. Most analyses assume n ≥ 1 and say so.
A Checklist for Early-Exit Loops
- Find every exit point:
return,break, and loop conditions that depend on data. - For each exit, note which loops it leaves.
- Describe the input that reaches an exit soonest and count its steps. This is the best case.
- Describe the input that avoids every exit for as long as possible and count its steps. This is the worst case.
- If you need an average, state the input distribution and then sum or integrate over it.
- Reduce each count to Θ separately, and name the case in your answer.
Exercise
The function below reports whether a list is sorted in non-decreasing order. For a list of length n ≥ 2, give the best-case and worst-case step counts, describe an input for each, and state each as a Θ bound. def is_sorted(items): steps = 0 for i in range(len(items) - 1): steps += 1 if items[i] > items[i + 1]: return False, steps return True, steps
Show answer
Best case: the first pair is out of order, for example [2, 1, 3, 4]. The loop returns after 1 step, which is Θ(1). Worst case: the list is sorted, or only its last pair is out of order, for example [1, 2, 3, 4] or [1, 2, 4, 3]. The loop runs all n - 1 iterations, which is Θ(n). A sorted list always costs the worst case, because the function can only answer True after checking every pair.
Exercise
In countuntilnegative, suppose there are r rows of c columns and each row contains exactly one negative value, placed at a uniformly random column independently of the other rows. What is the expected total step count, and what is its order of growth?
Show answer
A row whose negative value sits at column k (counting from 0) costs k + 1 steps. Averaging over c equally likely columns gives (c + 1) / 2 steps per row. Over r rows the expected total is r(c + 1) / 2, which is Θ(rc). The early break halves the constant but does not change the order of growth.
Exercise
A colleague writes: "has_duplicate is Θ(n²) because it has a triangular nested loop." Is this statement correct? Rewrite it so that it is accurate.
Show answer
It is not correct as stated, because the best case (a duplicate in the first two positions) takes 1 step, so not every input costs Θ(n²) steps. An accurate version: "has_duplicate has worst-case running time Θ(n²), reached when the list has no duplicates, and best-case running time Θ(1). Its running time is O(n²) for all inputs."