Sub topic 2
Reading operation costs
This chapter assumes you can write Python loops and functions, and that you have seen Big-O notation before. Here you will learn to read a cost table and use it to compare structures on the operations your problem needs.
What Big-O tells you
Big-O describes how the work for one operation grows as the input size n grows. It ignores constant factors and small inputs. It answers the question "what happens when the data gets 100 times bigger?" and does not answer "which one is faster today?"
Common classes, from cheapest to most expensive:
| Class | Name | Typical example |
|---|---|---|
| O(1) | Constant | Index into a list, dictionary lookup |
| O(log n) | Logarithmic | Binary search in a sorted list |
| O(n) | Linear | Scan a list for a value |
| O(n log n) | Linearithmic | Sorting |
| O(n²) | Quadratic | Nested loops over the same data |
Average case, worst case and amortized cost
A single cost number can hide three different ideas.
- Average case is the expected cost over typical inputs. A hash lookup is O(1) on average.
- Worst case is the cost on the most unlucky input. A hash lookup can degrade to O(n) when many keys collide.
- Amortized cost spreads an occasional expensive step over many cheap ones.
list.appendis O(1) amortized. Most appends are cheap, and the occasional resize copies the whole array.
When you read a cost, ask which of the three it is. A guarantee you can rely on under any input is a worst-case one.
Costs of operations on common structures
The same operation can cost very different amounts depending on the structure.
| Operation | List | Set / dict | Deque | Sorted list |
|---|---|---|---|---|
| Access by index | O(1) | not supported | O(n) in the middle | O(1) |
| Membership test | O(n) | O(1) average | O(n) | O(log n) |
| Add at end | O(1) amortized | O(1) average | O(1) | O(n) |
| Remove from front | O(n) | not applicable | O(1) | O(n) |
| Insert in middle | O(n) | not applicable | O(n) | O(n) |
The sorted-list column assumes binary search to find the position. Inserting still shifts elements, which is why it costs O(n).
Worked example: a membership test in a loop
Cost per operation matters most when the operation sits inside a loop. A single O(n) check is harmless, but n of them cost O(n²) in total.
names_list = ["ada", "grace", "alan"]
names_set = set(names_list)
print("grace" in names_list) # True, scans the list: O(n)
print("grace" in names_set) # True, hash lookup: O(1) on averageSuppose you check 100,000 incoming names against 100,000 known names. With a list, that is up to 10 billion comparisons. With a set, it is about 100,000 lookups, plus the one-time cost of building the set.
To estimate a whole algorithm, multiply the cost of each operation by how often it runs, then add the terms. The largest term dominates.
Common errors when reading costs
- Hidden linear work.
x in some_list,list.pop(0)andlist.insert(0, x)all look like single steps but cost O(n). - Quoting the average as a guarantee. If adversarial input is possible, hash collisions matter.
- Ignoring build cost. Converting a list to a set costs O(n). It pays off only when you query many times.
- Treating Big-O as a speed ranking. For small
n, an O(n) scan of a list can beat a hash lookup. Chapter on memory layout covers why.
Exercise
Exercise
A program builds a list of 50,000 user IDs. It then checks 50,000 incoming IDs, one at a time, to see whether each is in that list. Estimate the total cost, and name one change that lowers it.
Show answer
Each membership test on a list is O(n), and it runs n times, so the total is O(n²), about 2.5 billion comparisons in the worst case. Convert the list to a set once, which costs O(n). Each of the 50,000 checks then costs O(1) on average, so the total is O(n).
Exercise
A loop removes items from the front of a list with pop(0) until it is empty. What is the total cost for n items, and which structure fixes it?
Show answer
Each pop(0) shifts every remaining element, so it costs O(n). Over n removals the total is O(n²). A collections.deque removes from the front in O(1) with popleft(), which makes the total O(n).