Best, average, worst case
Beginner · 6 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The same code can be quick on a lucky input and painfully slow on an unlucky one. Best, average and worst case describe those three days. Worst case matters most to app builders, because it is what your busiest and unluckiest user experiences.
Practical use cases
- Web app: Sale-day checkout slowdown. On a normal day most carts are small and the stock check finishes quickly, so the average looks great. On a big sale, many customers hold huge carts at the same moment and the slowest path is hit again and again. Planning for the worst case, not the average, is what keeps checkout alive when traffic spikes.
- Web app: Searching a contact list. A phone-book screen looks for a name by scanning the list from the top. If the person is first, it is instant; if they are last or missing, every contact is checked. Knowing this, you add a keyed lookup so that even the unlucky name returns quickly and users never see a spinner.
- System: Service promises to customers. A company promising that pages load within two seconds must be sure about the slowest case, not just the usual one. Engineers test with the worst realistic data, such as the biggest account or the longest list, and promise only what that test can deliver.
The story: The Lucky Locker
Mira had lost her tiffin token somewhere in the row of six school lockers. Mrs. Sharma said, "Open them from the left, one by one." Mira groaned. "Madam, how long will that take?"
Mrs. Sharma laughed. "Depends on your luck. If the token is in the first locker, you finish after one look. If it is in the last one, or nowhere at all, you open every locker. And on most days, it will be somewhere in the middle."
Kabir, her brother, took notes like a cricket scorer. "So there are three scorecards: the best case (lucky), the worst case (unlucky) and the average case (a normal day)." Mrs. Sharma nodded. "When you build an app for a million people, never promise based on the lucky day. Promise based on the unlucky one, and be pleasantly surprised."
Mira found her token in locker 4 that afternoon. A middling day. And now she knew how to describe the whole search honestly: it never takes more than six looks, it often takes about three and a half, and once in a while it takes just one.
How to spot this problem, and where you need it
Your feature looks fast in everyday testing, yet a few users or a few busy hours suffer long delays or timeouts, and the average response time hides it.
Signs you need it
- Most requests finish quickly but a small group of users, usually those with the most data, complain about timeouts.
- Your code stops early when it finds something, so speed depends heavily on where the item sits or whether it exists at all.
- Monitoring shows a healthy average but a terrible slowest one percent of requests.
- A problem statement says guarantee, at most, or never slower than, which asks for worst-case thinking.
Where to use it in a project
- Load-testing a checkout, search or report with the biggest customer account instead of a demo account.
- Writing service promises, timeouts and retry limits for an API that other teams depend on.
The solution
For each important feature, write down three inputs: the luckiest, a typical one and the unluckiest. Run or reason about all three. If the unlucky one is far worse, change the approach so the gap shrinks, for example by using a keyed lookup or an index instead of scanning. Set timeouts and promises from the worst case, and watch the slowest requests, not just the average.
Payoff: Before: average page time looks fine at 0.3 seconds, yet big accounts wait 12 seconds. After: worst case is tuned to under 2 seconds.
Explain it like I am 8
You lost a toy in a row of boxes. Sometimes it is in the first box (lucky!). Sometimes it is in the last box (unlucky). Usually it is somewhere in the middle. Grown-ups count all three days and mostly worry about the unlucky one.
How it works, step by step
- Pick one algorithm and one input size, for example linear search through
nitems. - Best case: imagine the luckiest input. The target is the first item, so one check.
- Worst case: imagine the unluckiest input. The target is last (or missing), so
nchecks. - Average case: imagine every position equally likely, and take the typical number of checks, about half of
n. - Report the worst case (that is what Big-O usually describes) and mention the others if they differ a lot.
The code in four languages
PHP
<?php
// Linear search that also reports how many looks it needed.
function search(array $items, int $target): array {
$looks = 0;
foreach ($items as $i => $v) {
$looks++;
if ($v === $target) return [$i, $looks];
}
return [-1, $looks]; // not found: we looked at everything
}
$lockers = [7, 3, 9, 4, 8, 2];
echo "Best case (token 7): " . search($lockers, 7)[1] . " look
";
echo "Worst case (token 2): " . search($lockers, 2)[1] . " looks
";
echo "Missing (token 5): " . search($lockers, 5)[1] . " looks
";
// Average case: try every possible position and take the mean.
$total = 0;
foreach ($lockers as $t) $total += search($lockers, $t)[1];
echo "Average case: " . ($total / count($lockers)) . " looks
";JavaScript
// Linear search that also reports how many looks it needed.
function search(items, target) {
let looks = 0;
for (let i = 0; i < items.length; i++) {
looks++;
if (items[i] === target) return [i, looks];
}
return [-1, looks]; // not found: we looked at everything
}
const lockers = [7, 3, 9, 4, 8, 2];
console.log("Best case (token 7): " + search(lockers, 7)[1] + " look");
console.log("Worst case (token 2): " + search(lockers, 2)[1] + " looks");
console.log("Missing (token 5): " + search(lockers, 5)[1] + " looks");
// Average case: try every possible position and take the mean.
let total = 0;
for (const t of lockers) total += search(lockers, t)[1];
console.log("Average case: " + total / lockers.length + " looks");Java
public class Main {
// Linear search that also reports how many looks it needed: {index, looks}.
static int[] search(int[] items, int target) {
int looks = 0;
for (int i = 0; i < items.length; i++) {
looks++;
if (items[i] == target) return new int[]{i, looks};
}
return new int[]{-1, looks}; // not found: we looked at everything
}
public static void main(String[] args) {
int[] lockers = {7, 3, 9, 4, 8, 2};
System.out.println("Best case (token 7): " + search(lockers, 7)[1] + " look");
System.out.println("Worst case (token 2): " + search(lockers, 2)[1] + " looks");
System.out.println("Missing (token 5): " + search(lockers, 5)[1] + " looks");
// Average case: try every possible position and take the mean.
int total = 0;
for (int t : lockers) total += search(lockers, t)[1];
System.out.println("Average case: " + (double) total / lockers.length + " looks");
}
}Go
package main
import "fmt"
// search is a linear search that also reports how many looks it needed.
func search(items []int, target int) (index, looks int) {
for i, v := range items {
looks++
if v == target {
return i, looks
}
}
return -1, looks // not found: we looked at everything
}
func main() {
lockers := []int{7, 3, 9, 4, 8, 2}
_, looks := search(lockers, 7)
fmt.Println("Best case (token 7):", looks, "look")
_, looks = search(lockers, 2)
fmt.Println("Worst case (token 2):", looks, "looks")
_, looks = search(lockers, 5)
fmt.Println("Missing (token 5):", looks, "looks")
// Average case: try every possible position and take the mean.
total := 0
for _, t := range lockers {
_, looks := search(lockers, t)
total += looks
}
fmt.Println("Average case:", float64(total)/float64(len(lockers)), "looks")
}Time: Best O(1), average O(n), worst O(n) · Extra space: O(1). For linear search the lucky day is one look, the typical day is about half the list, and the unlucky day is the whole list.
Watch out for
- Quoting the best case as "the speed" of an algorithm. It is the least useful of the three.
- Mixing up "worst case" with "slowest machine". It is about the worst input, not the worst computer.
- Assuming average and worst are always the same. For quicksort they are very different.
Quick check
- Linear search over n items: what is the worst case?
- 1 check
- About n/2 checks
- n checks (last item or missing)
- Which case does Big-O usually describe by default?
- The worst case
- The best case
- Always the average
- The target is the very first item. This is the...
- Worst case
- Best case
- Average case