Foundations
Big-O notation
Measuring cost by how it grows, not by seconds
If you measure an algorithm in seconds, you're really measuring your laptop. Big-O throws away hardware, language, and constant factors and keeps the one thing that survives all of them: how does the work grow as the input grows? Double the input - does the work stay flat, double, or explode?
The core question
Watch the curves race
Drag the slider to grow the input size . Each curve is a complexity class; the readout shows exactly how many operations each one costs at your chosen . Push up and watch the classes fan apart - the whole story of Big-O is in that fan.
| class | operations at n = 8 |
|---|---|
| O(1) | 1 |
| O(log n) | 3 |
| O(n) | 8 |
| O(n log n) | 24 |
| O(n²) | 64 |
| O(2ⁿ) | 256 |
The gap is everything
The classes you'll meet, best to worst
| Class | Name | Doubling n means... | Typical example |
|---|---|---|---|
| O(1) | constant | no change | array index, hash lookup |
| O(log n) | logarithmic | +1 step | binary search |
| O(n) | linear | doubles | scan a list |
| O(n log n) | linearithmic | a bit more than doubles | merge sort, quicksort |
| O(n²) | quadratic | ×4 | nested loops, bubble sort |
| O(2ⁿ) | exponential | squares (!) | brute-force subsets |
The two simplification rules
Big-O deliberately blurs detail. Two rules do the blurring:
- Drop constant factors. and are both O(n) - because as grows, the constant stops mattering to the shape.
- Keep only the dominant term. is O(n²) - the term eventually dwarfs the rest.
The formal definition (it's friendlier than it looks)
# O(n): one pass
for x in items: # runs n times
print(x)
# O(n^2): a loop inside a loop
for x in items: # n times ...
for y in items: # ... n times each = n*n
compare(x, y)Check yourself
A loop over n items, each iteration running another full loop over the same n items, is:
Under Big-O, the cost 6n² + 500n + 9999 simplifies to:
Recall: why do we drop the constant factor and the lower-order terms?
Try to state it, then check.
Lock it in
- Big-O measures how an algorithm's cost grows with input size, not seconds on any one machine.
- Two rules do the blurring: drop constant factors, keep only the dominant term.
- The classes best to worst: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ) - and the gap between them is everything.
- Formally f(n) = O(g(n)) when f never exceeds a constant multiple of g past some n₀, which is why small-n detail is ignored.
Primary source
Ask your teacher