Big-O notation
Counting steps instead of seconds, and what the common growth rates feel like.
Updated
Seconds depend on the machine. Steps do not. Big-O describes how the number of steps grows as
the input size n grows, ignoring constant factors.
The common growth rates
| Notation | Name | Example |
|---|---|---|
O(1) | constant | read an array element |
O(log n) | logarithmic | binary search |
O(n) | linear | scan a list |
O(n log n) | linearithmic | merge sort |
O(n²) | quadratic | compare every pair |
Drag the slider to see how far apart the rates drift as n grows:
O(1) 1
O(log n) 4
O(n) 16
O(n²) 256
Steps for one run. Bars use a log scale so all four stay visible.
Reading code for its growth rate
def has_duplicate(items):
for i, a in enumerate(items):
for b in items[i + 1:]:
if a == b:
return True
return False
Two nested loops over the same input: O(n²). A set brings it down to O(n) at the cost of
O(n) extra memory.
What gets dropped
Constants and lower-order terms: 3n² + 10n + 7 is O(n²). They still matter for small n.
Worst, average, amortised
- Worst case: the upper bound for any input of size
n. - Average case: expected cost over a distribution of inputs.
- Amortised: average cost per operation over a sequence, such as appending to a dynamic array.