Count the simple operations a piece of code performs as the input grows.
Use it when you must say how much work code does, or whether it fits a time limit. Signal words: how many times does this line run, a loop inside a loop, keeps halving the input.
Start pick one basic step, such as a comparison or an addition, and a counter that starts at zero.
Step put the counter on the basic step. Inside a loop it runs once per pass. Nested loops multiply the passes, and loops one after the other add them.
Stop read the counter after the code finishes, for several sizes, and compare with the formula you expect.
It does not tell you the time by itself. It assumes every counted step costs about the same, and it ignores work hidden inside a call.
Cost: counting by running costs as much as the code itself. The formula is what lets you skip the run: n(n-1)/2 for the pair loop, floor(log2 n) for the halving loop.
In this lesson you learn to count what code does. You pick one basic step, such as a comparison, and you count how many times the code runs it. You count by running instrumented code on real sizes.
You work on a monitoring system. A nightly job reads the 200,000 alert ids of one busy day. It must flag any id that appears twice, because a duplicate means an alert was sent two times.
Your first version compares each id with every id after it. Each comparison is one check. The job has a budget of 2 seconds, and the team plans with an estimate of 100,000,000 simple steps a second.
Your team lead says: Before you ship this, tell me how many checks it makes and whether it fits the budget.
Here is a short test: 5 ids, so you can count by hand.
So the task is this: count the checks the job makes, for 5 ids and for 200,000.
At a meeting of 5 people, everyone shakes hands once with everyone else. The first person shakes 4 hands, the next one 3 new hands, then 2, then 1. That is 4 + 3 + 2 + 1 = 10 handshakes.
A handshake is one check, and a person is one id. The count follows from the rule of the meeting, so you can find it without watching a single handshake.
Like handshakes at a meeting: five people shake hands once with each other, four then three then two then one, ten in all.
Before you write code, count the checks for 5 ids by hand. The player below lists every check.
Solve it by hand: Five ids: count every check. The hand-solve sheet loads in your browser.
First count the way most people do. Take each id in turn, and pair it with every id after it.
The ids are numbered 0 to 4. Each row is one check, in the order the code makes it.
| Check | First id | Second id |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 0 | 2 |
| 3 | 0 | 3 |
| 4 | 0 | 4 |
| 5 | 1 | 2 |
| 6 | 1 | 3 |
| 7 | 1 | 4 |
| 8 | 2 | 3 |
| 9 | 2 | 4 |
| 10 | 3 | 4 |
The first id makes 4 checks, the second 3, the third 2 and the fourth 1. The last id makes none. The total is 10 checks for 5 ids.
Start with a correct version. Compare each id with every later id, and report a duplicate as soon as two match.
def has_duplicate(ids):
n = len(ids)
for a in range(n): # each id in turn
for b in range(a + 1, n): # every id after it
if ids[a] == ids[b]: # one check
return True
return FalseThis is correct. When no id repeats, it never exits early, so it makes every check: n(n-1)/2 of them.
Now check the real size.
The day has 200,000 ids, and the estimate is about 100,000,000 checks a second.
Here is the count:
So the job takes about 3 minutes and 20 seconds, and the budget is 2 seconds. It is 100 times too slow.
Predict the cost
Q The day has 200,000 ids and the job makes every pair check at 100,000,000 checks a second. About how long does it run?
Answer: C
There are 200,000 × 199,999 / 2 = 19,999,900,000 checks. At 100,000,000 a second that is about 200 seconds.
You found this without running the job. The next step is to learn the counting rule that gave you the number.
Can you count faster than listing the checks? Look at the table of 5 ids again. The first id makes 4 checks, the next 3, then 2 and 1. The pattern is a staircase.
For n ids the staircase is (n − 1) + (n − 2) + … + 1. Two copies of it laid side by side make n rows of n − 1 checks each, so one copy is n(n − 1) / 2.
Check the formula on a run. The counts below come from running the nested loop with a counter:
| Ids n | Checks the loop made | n(n − 1) / 2 |
|---|---|---|
| 5 | 10 | 10 |
| 10 | 45 | 45 |
| 100 | 4,950 | 4,950 |
| 1,000 | 499,500 | 499,500 |
Two nested loops do not always cost n × n. The inner loop here starts after the outer index, so the total is about half of n × n. Ten times more ids means about 100 times more checks.
Race: Steps of three loops as n grows. The operation counter loads in your browser.
The race counts the steps of three loops by running them. At 5,000 items the single loop makes 5,000 steps, the pair loop makes 12,497,500, and the halving loop makes 12.
The pair loop on five ids: id zero makes four checks, id one three, id two two, id three one, and the counter ends at ten.
A loop that halves its input is the third shape. The input is 40, and the loop runs while the number is above 1, cutting it in half each time. The player stops at four steps and asks you to predict.
Dry run: Predict each pass: a loop that halves 40. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Pass | n before | n after | Passes so far |
|---|---|---|---|
| 1 | 40 | 20 | 1 |
| 2 | 20 | 10 | 2 |
| 3 | 10 | 5 | 3 |
| 4 | 5 | 2 | 4 |
| 5 | 2 | 1 | 5 |
The loop runs 5 times for n = 40. Doubling the input to 80 would add only one pass.
Run the three shapes on three sizes. Every number comes from a run with a counter.
| Shape | n = 10 | n = 100 | n = 1,000 |
|---|---|---|---|
| One loop over n items | 10 | 100 | 1,000 |
| Two nested loops over n items | 100 | 10,000 | 1,000,000 |
| Each item with every later item | 45 | 4,950 | 499,500 |
| Halving until 1 | 3 | 6 | 9 |
Look at the columns. The single loop grows ten times for every ten times more items. The nested loops grow a hundred times. The halving loop adds about three passes.
Exercise · Predict the output: How many checks does it make?. The ids hold a duplicate. This loop records the first matching pair and keeps going. What does it print: the checks, then the two positions?
ids = [5, 2, 9, 2, 7]
checks = 0
first = -1
second = -1
for a in range(len(ids)):
for b in range(a + 1, len(ids)):
checks += 1
if ids[a] == ids[b] and first < 0:
first = a
second = b
print(checks, first, second)Here is the rule that gives every count in this lesson. Both templates use it.
A step inside a loop runs once for every pass, so nested loops multiply the passes and loops one after the other add them.
Choose the basic step first. Then add a counter at that step and nothing else. The counter at the end is the number of times the step ran.
Use it when you must say how much work code does, or whether it fits a time limit. Signal words: how many times does this line run, a loop inside a loop, keeps halving the input.
Start: pick one basic step, such as a comparison or an addition, and a counter that starts at zero.
Step: put the counter on the basic step. Inside a loop it runs once per pass. Nested loops multiply the passes, and loops one after the other add them.
Stop: read the counter after the code finishes, for several sizes, and compare with the formula you expect.
It does not tell you the time by itself. It assumes every counted step costs about the same, and it ignores work hidden inside a call.
Cost: counting by running costs as much as the code itself. The formula is what lets you skip the run: n(n-1)/2 for the pair loop, floor(log2 n) for the halving loop.
The count for 200,000 ids is more than 2 billion, so the template returns a 64-bit integer.
def count_pair_checks(n):
# [1] Start the counter at zero: nothing has been checked yet.
checks = 0
# [2] Take each item in turn as the first of a pair.
for a in range(n):
# [3] Pair it only with the items after it, so each pair is met once.
for b in range(a + 1, n):
# [4] One check for this pair.
checks += 1
# [5] Return the number of checks the loops made.
return checkspublic long countPairChecks(int n) {
// [1] Start the counter at zero: nothing has been checked yet.
long checks = 0;
// [2] Take each item in turn as the first of a pair.
for (int a = 0; a < n; a++) {
// [3] Pair it only with the items after it, so each pair is met once.
for (int b = a + 1; b < n; b++) {
// [4] One check for this pair.
checks++;
}
}
// [5] Return the number of checks the loops made.
return checks;
}long long countPairChecks(int n) {
// [1] Start the counter at zero: nothing has been checked yet.
long long checks = 0;
// [2] Take each item in turn as the first of a pair.
for (int a = 0; a < n; a++) {
// [3] Pair it only with the items after it, so each pair is met once.
for (int b = a + 1; b < n; b++) {
// [4] One check for this pair.
checks++;
}
}
// [5] Return the number of checks the loops made.
return checks;
}function countPairChecks(n) {
// [1] Start the counter at zero: nothing has been checked yet.
let checks = 0;
// [2] Take each item in turn as the first of a pair.
for (let a = 0; a < n; a++) {
// [3] Pair it only with the items after it, so each pair is met once.
for (let b = a + 1; b < n; b++) {
// [4] One check for this pair.
checks++;
}
}
// [5] Return the number of checks the loops made.
return checks;
}Rebuild the template: put its lines back in order. Loads in your browser.
A loop that cuts its input in half each time stops after floor(log2 n) passes. The template counts them by running the loop.
def count_halving_steps(n):
# [1] Start the counter at zero.
steps = 0
# [2] Keep going while there is more than one item left.
while n > 1:
# [3] Cut the input in half, rounding down.
n //= 2
# [4] One pass is done.
steps += 1
# [5] Return the number of passes.
return stepspublic int countHalvingSteps(int n) {
// [1] Start the counter at zero.
int steps = 0;
// [2] Keep going while there is more than one item left.
while (n > 1) {
// [3] Cut the input in half, rounding down.
n /= 2;
// [4] One pass is done.
steps++;
}
// [5] Return the number of passes.
return steps;
}int countHalvingSteps(int n) {
// [1] Start the counter at zero.
int steps = 0;
// [2] Keep going while there is more than one item left.
while (n > 1) {
// [3] Cut the input in half, rounding down.
n /= 2;
// [4] One pass is done.
steps++;
}
// [5] Return the number of passes.
return steps;
}function countHalvingSteps(n) {
// [1] Start the counter at zero.
let steps = 0;
// [2] Keep going while there is more than one item left.
while (n > 1) {
// [3] Cut the input in half, rounding down.
n = Math.floor(n / 2);
// [4] One pass is done.
steps++;
}
// [5] Return the number of passes.
return steps;
}Rebuild the template: put its lines back in order. Loads in your browser.
A loop that halves its input: marker two keeps going while more than one item is left, and marker three cuts in half and rounds down.
You can count any loop code in four steps.
Then check the two ends: what does the count give for no items, and for one?
Exercise · Put it in order: Counting every triple. Arrange the lines into a function that counts the triples of ids a < b < c, one check for each triple.
def count_triples(n):
checks = 0
for a in range(n):
for b in range(a + 1, n):
for c in range(b + 1, n):
checks += 1
return checks
for c in range(a + 1, n):A league has 12 teams, and every team plays every other team once. How many matches are there, and how many rounds of halving does it take to go from 12 teams to 1 winner in a knockout?
Template 1 counts the pairs: 12 × 11 / 2 = 66 matches. Template 2 halves 12 → 6 → 3 → 1: that is 3 passes (12 → 6, 6 → 3, 3 → 1).
Running both templates on 12 gives 66 and 3.
Real data brings edge cases.
With n = 0 or n = 1 there is no pair, so the pair loop makes 0 checks. The outer loop still starts, but the inner loop has nothing after it. The halving loop also makes 0 passes for n = 1, because n > 1 is false at once.
With n = 2 the pair loop makes exactly 1 check, and the halving loop makes 1 pass. The formula n(n-1)/2 gives 1, and so does floor(log2 2).
Take the loop of the first attempt, which stops at the first match. On the ids [4, 7, 4, 9] it makes 2 checks, not 6: the first id meets 7 and then 4, and stops. On 10 different ids it makes all 45 checks. The formula counts the worst case.
Exercise · Break it: Find the ids this check misses. This duplicate check saves work by comparing each id with the next one only. Find a list of ids with a duplicate where it says there is none.
def has_duplicate(ids):
for a in range(len(ids) - 1):
if ids[a] == ids[a + 1]:
return True
return FalseFor n = 200000 the count is 19,999,900,000, which is more than the largest 32-bit integer, 2,147,483,647. The templates return a 64-bit integer. A 32-bit counter in Java or C++ would wrap and give a wrong, even negative, answer.
This version reads "two nested loops" and says n × n without looking at the inner loop.
Counterexample: take an outer loop over 1,000 items whose inner loop starts after the outer index and stops after its first check. It makes 999 checks, not 1,000,000. The inner loop decides the count, not the number of loops.
Read the bounds of each loop, and read every exit.
A hidden loop: testing each new id against a list scans the list, so a thousand ids cost 499,500 comparisons, not a thousand.
This version starts the inner loop at a, not at a + 1. It checks each id against itself too.
Counterexample: for 5 ids the loops make 15 checks, not 10. Every id adds one self-check, so the count is n(n+1)/2. The error is n checks, which is small at large n but wrong by 50 percent at n = 5.
Start the inner loop after the outer index when each pair is met once.
This version says a loop that halves n runs ceil(log2 n) times.
Counterexample: for n = 33 the loop runs 33 → 16 → 8 → 4 → 2 → 1, which is 5 passes. The ceiling of log2(33) is 6. The loop rounds down at each cut, so the count is floor(log2 n).
Run the loop on a value slightly above a power of two to test your formula.
This version tests if id in seen on a list inside a loop over 1,000 ids and counts 1,000 steps.
Counterexample: the test on a list scans the list. Counting every comparison with a counter on the ids gives 499,500 comparisons for 1,000 new ids, not 1,000. The call is a loop of its own.
Ask of every call: does it loop inside?
Counting steps assumes each step costs about the same. A line that adds two numbers and a line that sorts a list of 1,000 numbers are each one line, yet the sort does thousands of steps inside.
Timed on one laptop, Python added two small integers in about 7 nanoseconds and sorted 1,000 random integers in about 30 microseconds, roughly 4,000 times longer. The figures depend on the machine. Count steps to compare two methods that do the same kind of step, and do not read the count as a time.
Your team lead brings three product changes. Each one asks you to count a new loop.
A fraud check compares every triple of ids, not every pair. The count is n(n-1)(n-2)/6: 10 for 5 ids, 161,700 for 100 and 166,167,000 for 1,000. A counted run of three nested loops agrees with the formula up to 100 ids.
A sampling job reads every second id. For 10 ids it makes 5 steps, for 1,000 it makes 500 and for 1,001 it makes 501. The count is ceil(n / 2): still a straight line in n.
A job first makes one pass over n ids, then runs the pair loop on all of them with the full n × n. The totals are 110 for n = 10, 1,001,000 for n = 1,000 and 4,002,000 for n = 2,000. The two parts add, and the larger part decides what matters at scale.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you count the steps of a loop and a nested loop. Then say what the count does not tell you. 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 pick one basic step and count how often it runs. A step in a loop runs once per pass, nested loops multiply the passes, and loops in a row add them.
Comparing each item with every later one makes n(n-1)/2 checks, which is 499,500 for 1,000 items. A loop that halves its input runs floor(log2 n) times.
I check the count by running the code with a counter. The count is steps, not seconds, and it misses loops hidden inside calls.
To say how much work some code does, I pick one basic step, such as a comparison, and count how often it runs. I do not guess from the look of the code. I put a counter on that step and run a few sizes.
A step inside a loop runs once for every pass. Nested loops multiply the passes, and loops one after the other add them. If each item is compared with every later item, the count is n times n minus 1, over 2. For 1,000 items that is 499,500 checks.
A loop that halves its input runs floor of log base 2 of n times. For a thousand items that is 9 passes, and doubling the input adds only one.
I also check the bounds, the early exits, and any call that loops inside, such as a membership test on a list.
The count is steps, not seconds, so I compare it with the time budget using the machine's step rate.
Checkpoint · Counting operations
Q1/10 You want to say how much work a piece of code does. What do you do first?
Answer: B
The count is of one basic step, such as a comparison. Lines and loops do not tell you how often a step runs.
Q2/10 A step sits inside a loop that runs 8 passes, and that loop sits inside a loop that runs 5 passes. Each pass of the outer loop runs the inner loop in full. How many times does the step run?
Answer: B
Nested loops multiply the passes: 5 × 8 = 40. Adding is for loops that run one after the other.
Q3/10 Each of 100 ids is compared once with every id after it. How many checks are made?
Answer: C
The count is n(n-1)/2 = 100 × 99 / 2 = 4,950. The full 10,000 counts every pair twice and every id with itself.
Q4/10 A job runs a loop over n items, then a second loop over the same n items. The loops are one after the other, with one step per pass. How many steps in all?
Answer: B
Loops one after the other add their passes: n + n = 2n. Only nesting multiplies.
Q5/10 A loop starts with n = 40 and runs while n > 1: n //= 2. How many passes does it make?
Answer: C
40 → 20 → 10 → 5 → 2 → 1 is five cuts. The count is floor(log2 40) = 5.
Q6/10 A loop starts with n = 33 and runs while n > 1: n //= 2. Which count is right?
Answer: A
33 → 16 → 8 → 4 → 2 → 1 is five passes. Each cut rounds down, so the count is the floor of the logarithm.
Q7/10 A pair loop is written for b in range(a, n) instead of range(a + 1, n). For n = 5 it makes 15 checks. Why is that more than 10?
Answer: C
Starting at a includes b = a, a check of an id against itself. That adds n checks: 10 + 5 = 15.
Q8/10 The code for id in ids: if id in seen_list: ... loops over 1,000 ids, and seen_list is a list that grows by one item each time. About how many comparisons does the membership test make in all, if no id repeats?
Answer: C
The test scans the list. The k-th test scans k items, and 0 + 1 + … + 999 = 499,500. A call can hide a loop.
Q9/10 Why is a step count not a promise about time?
Answer: B
A line that sorts 1,000 numbers and a line that adds two numbers are each one step, yet they differ by a factor of about a thousand.
Q10/10 In Java or C++, which type should hold the count of pair checks for 200,000 items?
Answer: C
The largest 32-bit integer is 2,147,483,647, below the count. A 32-bit counter would wrap.
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 | Count the checks in a nested scan | Shop | Easy | A pair loop with an early exit, counted exactly |
| 2 | Pairs compared in a roster | Chat | Easy | Nested loops inside groups, and groups side by side |
| 3 | Operations in a halving loop | Freight | Medium | A loop that halves, with work inside it |
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.