Big O by counting, not memorising
O(n²) and O(n log n) look like labels to memorise. They are not: you get them by counting how often the code does its basic step, then keeping only the part of the count that grows fastest.
01 What Big O measures
Big O does not tell you how many seconds code takes; that depends on the machine. It tells you how the amount of work grows as the input grows. If you double n, does the work double, quadruple, or barely change?
So the method is: pick the basic step (a comparison, a lookup, an addition), count how many times it runs for an input of size n, and simplify.
02 One loop: count the trips
The body runs once per item: n additions, plus a couple of fixed steps before and after. The count is n + 2. Double the list and the work doubles.
03 Nested loops multiply
To check a list for a repeated value the plain way, compare every pair. The inner loop starts just after i, so no pair is compared twice.
- position i
- position j, compared
Four numbers and no comparisons yet. Each pair of positions will be compared once.
In general the inner loop runs n − 1, then n − 2, … down to 0 times. That adds up to n(n − 1) / 2. For n = 4 it is 6, matching the count above.
04 Keep only the term that grows fastest
Multiply out the count: n(n − 1) / 2 = n²/2 − n/2. Now see what each part does as n grows.
| n | n² / 2 | n / 2 | Total comparisons |
|---|---|---|---|
| 10 | 50 | 5 | 45 |
| 100 | 5,000 | 50 | 4,950 |
| 1,000 | 500,000 | 500 | 499,500 |
The n/2 part becomes a rounding error. Drop it. Then drop the 1/2 in front, because a fixed factor does not change how the work grows: double n and n²/2 still quadruples, just like n². What is left is O(n²).
- Count the basic step for size
n. - Keep the term that grows fastest; drop the rest.
- Drop the constant factor in front of it.
05 Loops in a row add
Two loops one after the other cost n + n = 2n, which is still O(n). Sorting first and then scanning costs n log n + n, and the n log n term wins: O(n log n). Only loops inside loops multiply.
def contains_duplicate(nums):n = len(nums)for i in range(n):for j in range(i + 1, n):if nums[i] == nums[j]:return Truereturn False
def contains_duplicate(nums):seen = set()for x in nums:if x in seen:return Trueseen.add(x)return False
in and add takes about the same time however big the set is, on average.