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 pseudocode, and trace a loop by hand. Earlier chapters asked whether an algorithm is correct and whether it stops. Here the question is how much work it does as its input grows.
Counting basic steps
Running time in seconds depends on the machine, the language and the compiler. Those details describe a program, not an algorithm. To measure the algorithm, pick one basic step, an operation that takes roughly constant time, and count how many times it happens.
For a search, the natural basic step is one comparison. Here is linear search with a counter added:
def linear_search_counted(items, target):
comparisons = 0
for i, x in enumerate(items):
comparisons += 1
if x == target:
return i, comparisons
return -1, comparisons
data = [7, 3, 9, 4, 1]
print(linear_search_counted(data, 7)) # (0, 1) best case
print(linear_search_counted(data, 1)) # (4, 5) last element
print(linear_search_counted(data, 8)) # (-1, 5) not foundFor the same list, the count runs from 1 to 5. Because the cost depends on which input you get, you state which case you mean:
| Case | Comparisons for n items | When it happens |
|---|---|---|
| Best | 1 | Target is first |
| Worst | n | Target is last or absent |
| Average (target present, equally likely positions) | (n + 1) / 2 | Typical successful search |
The worst case is the usual default. It gives a guarantee that holds for every input.
From counts to Big-O
Exact counts get messy. A loop might do 3n + 5 operations once you include setup and the return. Big-O keeps only the growth rate. You drop constant factors and lower-order terms because they matter less and less as n grows.
Formally, f(n) is O(g(n)) if there are constants c and n₀ such that f(n) ≤ c · g(n) for all n ≥ n₀. So 3n + 5 is O(n), and n²/2 + 10n is O(n²).
| Growth | Name | Example |
|---|---|---|
| O(1) | Constant | Reading `xs[0]` |
| O(log n) | Logarithmic | Euclid's GCD, binary search |
| O(n) | Linear | Linear search, `find_max` |
| O(n²) | Quadratic | Comparing every pair of items |
A less obvious count: Euclid's algorithm
For Euclid's loop, the basic step is one mod operation. The count does not grow in step with the size of b. After any two iterations the first argument has dropped below half its old value, so the number of iterations is O(log b). This is why gcd stays fast on numbers with hundreds of digits.
Common errors
- Counting each line once when it sits inside a loop. A line inside a loop runs once per iteration.
- Multiplying the costs of loops that run one after another. Sequential loops add, O(n) + O(n) = O(n). Nested loops multiply, O(n) · O(n) = O(n²).
- Treating a library call as one step.
x in some_listis itself a linear search.
Exercise
A function loops over a list of n items and, for each item, loops again over the whole list to count how many items equal it. After that, a separate loop finds the maximum count. Give the worst-case number of equality comparisons and the overall Big-O.
Show answer
The nested loops perform n × n = n² equality comparisons. The final loop adds about n more comparisons, for a total near n² + n. Dropping the lower-order term gives O(n²).
Exercise
Why is linear search's worst case n comparisons when the target is absent, and what is its Big-O?
Show answer
The algorithm cannot conclude the target is missing until it has compared it with every one of the n items. So the worst case is n comparisons, which is O(n).