Tell which case a bound describes and which one an interviewer is asking for.
Use it when the cost of code depends on the input, or an interviewer asks how fast something is. Signal words: on average, worst case, already sorted, stops at the first match.
Start pick one input size n and one step to count, such as a comparison.
Step find the input that makes the count smallest and the input that makes it largest, and run the code on both.
Stop report the worst case with its input, and the best case if it helps. State the distribution before you give an average.
It does not pick the case for you. A latency promise needs the worst case, and a batch job that runs a million times may care about the average.
Cost: one extra run per case. The counts are exact for the inputs you ran.
In this lesson you learn that one piece of code has several costs, depending on the input. You learn to name the best, average and worst case, and to say which one a claim describes.
You work on a monitoring system. A service keeps a list of 1,000 registered device ids. To check a device, it scans the list from the start and stops at the first id that matches.
Your team lead asks whether this lookup is fast. A device near the front is found at once. A device at the back, or one that is not registered, needs the whole list.
Your team lead says: Give me one number for the cost of a lookup.
So the task is this: say what the cost is for the best input, the worst input and a typical input.
You look for a book on a shelf, reading each spine from the left, and you stop when you find it. If it is the first book, you read one spine. If it is the last, or not there, you read every spine.
The shelf is the same and the search is the same. The cost depends on where the book sits.
Like a book on a shelf: you read spines from the left and stop at the book, so the cost depends on where it sits.
Before you write code, count one lookup by hand. The list is 40, 12, 7, 33, 19 and the target is 33.
Solve it by hand: Comparisons of a linear lookup. The hand-solve sheet loads in your browser.
Each count is the number of comparisons made before the scan stops.
| Target | Where it sits | Comparisons |
|---|---|---|
| 40 | position 0, the first id | 1 |
| 19 | position 4, the last id | 5 |
| 99 | not in the list | 5 |
The same list and the same code give 1 or 5, depending on the target.
Start with a correct version. Scan from the start, count each comparison, and stop at the first match.
def comparisons_to_find(items, target):
count = 0
for x in items: # each id, from the front
count += 1 # one comparison
if x == target: # first match: stop here
break
return countIt is correct. The cost is not one number: it is the count for the input you give it.
Now check the real size.
The list has 1,000 ids, and the service makes 100,000 lookups an hour.
Here is the count, from running the function on the ids 0 to 999:
At 1,000 comparisons, 100,000 lookups make 100,000,000 steps, about one second at the planning rate. At 500.5 each they make about 50,050,000 steps.
Predict the cost
Q A list has 1,000 ids and every lookup misses, so the scan reads the whole list. How many comparisons do 100,000 lookups make?
Answer: C
Each miss makes 1,000 comparisons, and 100,000 × 1,000 is 100,000,000.
You answered with a count for a stated input, not with a feeling about the code.
Can one cost describe the code? Run the same sort on three inputs of the same size and see. Insertion sort moves each item left past larger items, and stops as soon as the item before it is not larger.
Here are the comparisons on 1,000 distinct numbers, counted by running the code.
| Input | Comparisons |
|---|---|
| Sorted, 0 to 999 | 999 |
| Reversed, 999 to 0 | 499,500 |
| One shuffled list (seed 7) | 258,975 |
The sorted list is the best case, n - 1 comparisons. The reversed list is the worst case, n(n-1)/2. The shuffled list sits in between, at about half of the worst case.
Race: Insertion sort: comparisons on three kinds of input. The operation counter loads in your browser.
The race counts comparisons at n = 10, 20, 40 and 80. At 80, a sorted list costs 79, a shuffled one 1,783 (seed 7), and a reversed one 3,160.
Insertion sort on a thousand items makes 999 comparisons on a sorted list and 499,500 on a reversed one.
Insertion sort runs on the list 3, 1, 2. The player stops before each comparison count and asks you to predict it.
Dry run: Predict each step: comparisons of insertion sort. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Step | Comparison | Total so far |
|---|---|---|
| 1 | 3 against 1: swap | 1 |
| 2 | 3 against 2: swap | 2 |
| 3 | 1 against 2: in place, stop | 3 |
That is 3 comparisons for this order.
Exercise · Predict the output: How many comparisons on this order?. Insertion sort runs on four numbers, and the code counts every comparison. What does it print?
a = [2, 4, 1, 3]
comparisons = 0
for i in range(1, len(a)):
j = i
while j > 0:
comparisons += 1
if a[j - 1] > a[j]:
a[j - 1], a[j] = a[j], a[j - 1]
j -= 1
else:
break
print(comparisons)An average is taken over inputs, so you must say which inputs. Take every order of the numbers 1, 2 and 3. There are 6 orders, and insertion sort makes these counts: 2, 3, 2, 3, 3 and 3. The total is 16, so the average is 16 divided by 6, which is 2.67.
For all 24 orders of four numbers, the total is 118 comparisons, an average of 4.92. For 20 shuffles of 1,000 numbers (seeds 0 to 19), the mean was 250,684 against 249,750 from the formula n(n-1)/4. A different set of inputs would give a different average.
Of the 24 orders of four items, 2 cost 3 comparisons, 6 cost 4, 8 cost 5 and 8 cost 6. Insertion sort is also cheap on nearly sorted data. A sorted list of 1,000 numbers with ten neighbouring pairs swapped (seed 3) costs 1,009 comparisons. With the smallest number moved to the end, it costs 1,997.
On eight items, a sorted list costs 7 comparisons, four swapped pairs cost 10 and a reversed list costs 28.
Binary search on the 1,000 sorted ids costs 1 comparison at best and 10 at worst, and an absent id also costs 10. Over the 1,000 present ids the mean is 8.987, because 489 ids need all 10 comparisons.
The formula n(n-1)/4 is the textbook average for a uniformly random order. Real data is rarely uniform, so say what you assume.
Here is the rule that keeps a bound honest. Both templates use it.
A bound promises a stated set of inputs: the best case is the cheapest input, the worst is the dearest, and an average needs its distribution stated.
For one input size n, the best case is the minimum count over all inputs and the worst case is the maximum. The average is a weighted sum, and the weights are the chances you state.
Use it when the cost of code depends on the input, or an interviewer asks how fast something is. Signal words: on average, worst case, already sorted, stops at the first match.
Start: pick one input size n and one step to count, such as a comparison.
Step: find the input that makes the count smallest and the input that makes it largest, and run the code on both.
Stop: report the worst case with its input, and the best case if it helps. State the distribution before you give an average.
It does not pick the case for you. A latency promise needs the worst case, and a batch job that runs a million times may care about the average.
Cost: one extra run per case. The counts are exact for the inputs you ran.
The function returns how many comparisons the scan makes before it stops. It stops at the first match, so the count depends on where the target sits.
def comparisons_to_find(items, target):
# [1] Start with no comparisons made.
count = 0
for x in items:
# [2] Compare the next id with the target, and count it.
count += 1
# [3] Stop at the first match: the rest of the list is never read.
if x == target:
break
# [4] Return the number of comparisons.
return countpublic int comparisonsToFind(int[] items, int target) {
// [1] Start with no comparisons made.
int count = 0;
for (int x : items) {
// [2] Compare the next id with the target, and count it.
count++;
// [3] Stop at the first match: the rest of the list is never read.
if (x == target) {
break;
}
}
// [4] Return the number of comparisons.
return count;
}int comparisonsToFind(vector<int>& items, int target) {
// [1] Start with no comparisons made.
int count = 0;
for (int x : items) {
// [2] Compare the next id with the target, and count it.
count++;
// [3] Stop at the first match: the rest of the list is never read.
if (x == target) {
break;
}
}
// [4] Return the number of comparisons.
return count;
}function comparisonsToFind(items, target) {
// [1] Start with no comparisons made.
let count = 0;
for (const x of items) {
// [2] Compare the next id with the target, and count it.
count++;
// [3] Stop at the first match: the rest of the list is never read.
if (x === target) {
break;
}
}
// [4] Return the number of comparisons.
return count;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Break it: Find the lookup whose cost it gets wrong. This should return how many comparisons the scan makes before it stops, including a scan that finds nothing. Find an input where it gives the wrong count.
def comparisons_to_find(items, target):
for i in range(len(items)):
if items[i] == target:
return i + 1
return 0Each new item moves left past larger items. The inner loop has an early exit, so a sorted list costs one comparison for each item.
def insertion_comparisons(values):
# [1] Work on a copy, and start with no comparisons made.
a = list(values)
comparisons = 0
# [2] Take each item from the second on, and move it left into place.
for i in range(1, len(a)):
j = i
while j > 0:
# [3] One comparison: is the item before the new one larger?
comparisons += 1
if a[j - 1] > a[j]:
a[j - 1], a[j] = a[j], a[j - 1]
j -= 1
else:
# [4] Early exit: the item is in place, so stop moving it.
break
# [5] Return the number of comparisons.
return comparisonspublic long insertionComparisons(int[] values) {
// [1] Work on a copy, and start with no comparisons made.
int[] a = values.clone();
long comparisons = 0;
// [2] Take each item from the second on, and move it left into place.
for (int i = 1; i < a.length; i++) {
int j = i;
while (j > 0) {
// [3] One comparison: is the item before the new one larger?
comparisons++;
if (a[j - 1] > a[j]) {
int t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
j--;
} else {
// [4] Early exit: the item is in place, so stop moving it.
break;
}
}
}
// [5] Return the number of comparisons.
return comparisons;
}long long insertionComparisons(vector<int>& values) {
// [1] Work on a copy, and start with no comparisons made.
vector<int> a = values;
long long comparisons = 0;
// [2] Take each item from the second on, and move it left into place.
for (size_t i = 1; i < a.size(); i++) {
size_t j = i;
while (j > 0) {
// [3] One comparison: is the item before the new one larger?
comparisons++;
if (a[j - 1] > a[j]) {
swap(a[j - 1], a[j]);
j--;
} else {
// [4] Early exit: the item is in place, so stop moving it.
break;
}
}
}
// [5] Return the number of comparisons.
return comparisons;
}function insertionComparisons(values) {
// [1] Work on a copy, and start with no comparisons made.
const a = values.slice();
let comparisons = 0;
// [2] Take each item from the second on, and move it left into place.
for (let i = 1; i < a.length; i++) {
let j = i;
while (j > 0) {
// [3] One comparison: is the item before the new one larger?
comparisons++;
if (a[j - 1] > a[j]) {
const t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
j--;
} else {
// [4] Early exit: the item is in place, so stop moving it.
break;
}
}
}
// [5] Return the number of comparisons.
return comparisons;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The sort that swaps equal items. On a list of equal numbers this insertion sort makes more comparisons than it should. Which line is wrong?
def insertion_comparisons(values):
a = list(values)
comparisons = 0
for i in range(1, len(a)):
j = i
while j > 0:
comparisons += 1
if a[j - 1] >= a[j]:
a[j - 1], a[j] = a[j], a[j - 1]
j -= 1
else:
break
return comparisonsThe early exit of insertion sort: when the item before the new one is not larger, the inner loop stops.
You can state any bound in four steps.
A check compares each id with the ids before it, and stops at the first equal pair. With 1,000 ids, two equal ids at the front make 1 comparison. With 1,000 distinct ids, the check makes 499,500.
Both counts came from running the loops. The best case is 1, the worst case is 499,500, and the exit does not help when no pair is equal.
Exercise · Put it in order: Stop at the first equal pair. Arrange the lines into a check that compares each id with the ids before it and stops at the first equal pair.
def has_equal_pair(ids):
for i in range(len(ids)):
for j in range(i):
if ids[i] == ids[j]:
return True
return False
for j in range(len(ids)):Real data brings edge cases.
For items = [] the scan makes 0 comparisons. Every case is 0, so best, average and worst agree. Template 1 returns 0.
For items = [7, 7, 7] and target = 7, the scan stops at the first 7 after 1 comparison. The later copies are never read, so the cost depends on the first match.
For items = [4, 8, 15, 16, 23, 42] and target = 99, the scan makes 6 comparisons, the same as the last id. A miss is as dear as the worst hit, and a list of mostly absent targets has an average close to n.
For values = [1] insertion sort makes 0 comparisons, because the loop starts at the second item. With one item the best and worst cases are both 0.
This version says insertion sort on 1,000 items makes about 499,500 comparisons, because that is what the textbook worst case gives.
Counterexample: one shuffled list of 1,000 distinct numbers (seed 7) made 258,975 comparisons, and a sorted list made 999. The 499,500 is the worst case, a reversed list. Say which input you mean.
This version says a linear lookup costs O(1), because it found the first id with one comparison.
Counterexample: on the ids 0 to 999, target 0 costs 1 comparison and target 999 costs 1,000. A claim for all inputs must hold for the dearest one.
Two wrong claims: reading the average as the worst case, and quoting the best case as the cost.
This version says the average lookup in 1,000 ids is 500.5 comparisons and stops there.
Counterexample: that average assumes each present id is equally likely. If 99 of every 100 lookups ask for the first id and the other one misses, the average is (99 × 1 + 1,000) / 100 = 10.99. If half the lookups ask for an absent id, it is 750.25. State the distribution.
This version says a duplicate check with an early exit is fast, because it stops when it finds a pair.
Counterexample: on 1,000 distinct ids no pair exists, so the exit never fires and the check makes 499,500 comparisons. The exit lowers only the cases that contain a pair.
Summing all items of a list reads every item, whatever the order. Its best, average and worst cases are all n steps, so there is nothing to separate.
Naming cases helps only when the input changes the count. When the count is the same for every input, say so, and move on.
Your team lead brings three product changes. Each one asks for a new case.
Half the lookups ask for an absent id. A present id costs 500.5 on average and an absent one costs 1,000, so the average is 0.5 × 500.5 + 0.5 × 1,000 = 750.25 comparisons.
The ids are kept sorted, so the service can halve the range at each step. The worst case drops from 1,000 comparisons to 10, which is floor(log2 1000) + 1. The best case stays at 1.
A job rejects a batch at the first repeated id. A batch with a repeat at the front costs 1 comparison, and a clean batch of 1,000 costs 499,500. Plan the budget for the clean batch.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate what the best, average and worst case of a lookup are, and which one you quote by default. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
I name the input first. For a linear lookup in 1,000 ids, the best case is one comparison and the worst case is 1,000.
The average needs a distribution. If every present id is equally likely it is 500.5, but if requests favour the front it is much lower.
I quote the worst case by default and name the input that causes it.
The cost of code depends on the input, so I name the case. The best case is the cheapest input of a size, and the worst case is the dearest. I run the code on both and count the step.
For a linear lookup in 1,000 ids, the best case is one comparison and the worst case is 1,000. For insertion sort on 1,000 items, a sorted list took 999 comparisons and a reversed list took 499,500.
An average is an expectation, so I state the inputs. With every present id equally likely, the lookup averages 500.5 comparisons. A different mix of requests gives a different average.
An early exit helps the best case and not the worst. I quote the worst case by default, with the input that causes it, and add the average only with its distribution.
Checkpoint · Best, average and worst case
Q1/10 A linear lookup scans 1,000 ids and stops at the first match. How many comparisons does it make at best and at worst?
Answer: B
The first id matches after one comparison. The last id, or an absent id, needs all 1,000.
Q2/10 Every present id in a list of 1,000 is equally likely to be the target. What is the average number of comparisons?
Answer: C
The counts run from 1 to 1,000, so the total is 500,500 and the average is 500.5.
Q3/10 Which input is the worst case of insertion sort?
Answer: A
A reversed list makes every new item move all the way left: n(n-1)/2 comparisons.
Q4/10 Insertion sort made 999 comparisons on a sorted list of 1,000 items. What does that number show?
Answer: C
A sorted list makes one comparison for each item after the first, and every new item stops at once.
Q5/10 Over all 6 orders of 3 items insertion sort makes 16 comparisons in total. What is the average?
Answer: C
The average is the total divided by the number of inputs: 16 / 6.
Q6/10 A reviewer says the average lookup is 500.5 comparisons. What must you ask first?
Answer: C
An average is an expectation over stated inputs. Skewed requests give a different average.
Q7/10 A duplicate check with an early exit runs on 1,000 distinct ids. How many comparisons does it make?
Answer: C
No pair is equal, so the exit never fires and every pair is compared: n(n-1)/2.
Q8/10 A service promises that each request finishes within a limit. Which case do you plan for?
Answer: C
A promise for every request must hold for the dearest input.
Q9/10 Half the lookups miss, and a miss costs 1,000 comparisons. A present id averages 500.5. What is the overall average?
Answer: D
0.5 × 500.5 + 0.5 × 1,000 = 750.25.
Q10/10 An interviewer asks for the complexity of a lookup and you answer "O(1)" because the first id matched. What is wrong?
Answer: B
A bound for all inputs must hold for the worst input: the last or an absent id.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Linear search cost on average | Maps | Easy | Total and average comparisons over stated lookups |
| 2 | Worst case of an early exit | Feed | Medium | Exact count of a nested check that stops early |
| 3 | Quick sort on sorted input | Store | Medium | Why the worst input of a first-pivot quick sort is a sorted list |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.