Video lecture
Watch on YouTube(opens in a new tab)Sub topic 14
How Much Work? Counting Steps and Big-O
This chapter assumes you can read simple Python, follow a loop by hand with a state table, and have seen the linear search, find_max and Euclid's gcd examples from earlier chapters. You will learn to estimate how much work an algorithm does by counting basic steps, and to state that estimate in Big-O notation.
Correctness and termination tell you that an algorithm finishes with the right answer. They don't tell you whether it finishes in a millisecond or a week. Two correct algorithms for the same problem can differ in cost by a factor of millions on large inputs, so cost belongs in an algorithm's description too.
Why Count Steps Instead of Timing
You could run a program and time it with a stopwatch. That measures a program on one machine, with one compiler or interpreter, on one input. Change any of those and the number changes. A description of an algorithm should hold for every implementation, so you need a measure that ignores the machine.
The standard approach has three parts:
- Choose a basic operation, the step that dominates the work. Examples are a comparison, an arithmetic operation, or one loop iteration.
- Choose a measure of input size, usually written
n. Examples are the length of a list or the number of digits in a number. - Count how many basic operations the algorithm performs, as a function of
n.
This count is called the algorithm's running time, even though it is measured in steps, not seconds.
Counting Steps in Practice
A single loop: linear search
Take comparisons x == target as the basic operation and the list length as n. Instrumenting the code lets you check your count:
def linear_search_count(items, target):
comparisons = 0
for i, x in enumerate(items):
comparisons += 1
if x == target:
return i, comparisons
return -1, comparisons
data = list(range(1, 11)) # n = 10
print(linear_search_count(data, 1)) # (0, 1) target is first
print(linear_search_count(data, 10)) # (9, 10) target is last
print(linear_search_count(data, 99)) # (-1, 10) target is absentThe count depends on the input as well as its size. That leads to three different questions:
| Case | Meaning | Linear search comparisons |
|---|---|---|
| Best case | Cheapest input of size n | 1 (target at index 0) |
| Worst case | Most expensive input of size n | n (target last or absent) |
| Average case | Expected cost over a stated input distribution | about (n + 1) / 2 if the target is present and equally likely at each position |
When people state an algorithm's cost without saying which case they mean, they almost always mean the worst case. It gives a guarantee: no input of size n costs more.
Every element, always: find_max
find_max from the loop invariant chapter compares each of xs[1:] against best. For a list of length n that is exactly n − 1 comparisons, whatever the values are. The best, worst and average cases are all the same. The assignment best = x runs anywhere from 0 to n − 1 times, depending on the order of the values. That is why you pick one basic operation: the comparison count is exact and it bounds everything else in the loop.
Nested loops: checking for duplicates
def has_duplicate(xs):
comparisons = 0
n = len(xs)
for i in range(n):
for j in range(i + 1, n):
comparisons += 1
if xs[i] == xs[j]:
return True, comparisons
return False, comparisons
print(has_duplicate([3, 1, 4, 5, 9])) # (False, 10)
print(has_duplicate([3, 3, 4, 5, 9])) # (True, 1)In the worst case (no duplicates), the inner loop runs n − 1 times, then n − 2, and so on down to 0. The sum is n(n − 1) / 2. For n = 5 that gives 10, which matches the output.
Big-O Notation
Exact counts like n(n − 1) / 2 carry more detail than you usually need. On large inputs, the term that grows fastest decides the cost, and constant factors depend on the machine anyway. Big-O keeps only the growth rate.
Definition. A function f(n) is O(g(n)) if there are constants c > 0 and n₀ such that f(n) ≤ c · g(n) for all n ≥ n₀.
In words, for large enough n, f grows no faster than a constant multiple of g. Applied to the examples above:
- Linear search, worst case:
f(n) = n. Takec = 1, so it isO(n). find_max:f(n) = n − 1 ≤ n, so it isO(n).has_duplicate, worst case:f(n) = n(n − 1)/2 ≤ n²/2. Takec = 1/2, so it isO(n²).
The working rules follow from the definition:
- Drop constant factors:
5nisO(n). - Keep the dominant term:
3n² + 10n + 7isO(n²), because forn ≥ 1it is at most20n². - Steps in sequence add, and the larger term wins: an
O(n)loop followed by anO(n²)loop isO(n²). - Nested loops multiply: an outer loop of
niterations around an inner loop ofO(n)work isO(n²).
The common classes, from cheapest to most expensive:
| Class | Name | Typical shape | Example |
|---|---|---|---|
| O(1) | Constant | Fixed number of steps | Reading `xs[0]` |
| O(log n) | Logarithmic | Problem shrinks by a constant factor each step | Euclid's algorithm, binary search |
| O(n) | Linear | One pass over the input | Linear search, `find_max` |
| O(n log n) | Linearithmic | Divide in halves, linear work per level | Merge sort |
| O(n²) | Quadratic | All pairs | `has_duplicate` |
| O(2ⁿ) | Exponential | All subsets | Brute-force subset sum |
A Harder Count: Euclid's Algorithm
The loop in gcd has no fixed iteration count, so you count iterations with a decreasing measure, as in the termination chapter. This time you also ask how fast the measure decreases.
def gcd_steps(a, b):
steps = 0
while b != 0:
a, b = b, a % b
steps += 1
return a, steps
print(gcd_steps(48, 18)) # (6, 3)
print(gcd_steps(89, 55)) # (1, 9)The key fact: after any two iterations, the second argument drops to less than half its earlier value. Let (a, b) be the state at some point, with a ≥ b > 0 (this holds after the first iteration). Two iterations later, the second argument is a mod b. If b ≤ a/2, then a mod b < b ≤ a/2. If b > a/2, then a mod b = a − b < a/2. Either way, the value is below half of a, which was the second argument two iterations earlier. Halving every two steps means at most about 2 log₂ b iterations, so Euclid's algorithm is O(log min(a, b)).
Consecutive Fibonacci numbers such as 89 and 55 are the worst case. Each remainder is the previous Fibonacci number, so the values shrink as slowly as possible.
Gotchas and Common Errors
- Wrong input size. For number algorithms, the natural size is the number of digits
d, not the value. Euclid isO(log b)in the value, which isO(d): linear in the length of the input. A loop that tries every divisor up toblooks likeO(b), which sounds linear but is exponential ind. - Hidden costs in one line.
x in some_list,xs[1:], andsorted(xs)each do more than one step.xs[1:]infind_maxcopiesn − 1elements. That doesn't change O(n), but the same slice inside a loop would push the cost to O(n²). - Unit-cost arithmetic. Counting
a % bas one step assumes fixed-size integers. Python integers have no size limit, and for very large values one%costs time that grows with the number of digits. - Constants still matter at small n. An O(n²) algorithm with tiny constants can beat an O(n log n) one on a list of 20 items. Big-O describes growth, not which algorithm is faster on a given input.
- Unstated case. "Linear search is O(1)" is true only for the best case. Always say which case you mean when it isn't the worst.
- Adding instead of multiplying. Nested loops multiply their counts. Sequential loops add their counts.
Exercise
Instrument find_max to count comparisons, run it on [7, 2, 9, 4, 1], and state the count as a formula in n and as a Big-O class. Does the order of the elements change the count?
Show answer
Add a counter that increments before if x > best. The list has n = 5, so the function makes 4 comparisons. In general it makes n − 1 comparisons, which is O(n), and in fact Θ(n). The order of the elements never changes the comparison count. It changes only how many times best = x runs, from 0 to n − 1 times.
Exercise
A function runs a loop of n iterations that each call linearsearch on the same list of length n, then runs findmax once on that list. Give its worst-case comparison count and its Big-O class.
Show answer
The loop does n × n = n² comparisons in the worst case, and findmax adds n − 1 more. The total is n² + n − 1, which is O(n²): the sequential findmax term is dominated, and the nested part multiplies.
Exercise
An algorithm decides whether a positive integer m is prime by testing every divisor from 2 to m − 1. Why is it misleading to call this algorithm "linear"?
Show answer
It makes up to m − 2 divisions, which is O(m) in the value of m. But the input size is the number of digits d, which is about log₁₀ m, so m is about 10^d. In terms of the actual input size, the cost is exponential, O(10^d).