Big-O notation describes how the amount of work grows as the input gets larger. It ignores constant factors and small inputs, and answers one question: what happens when n becomes ten or a thousand times bigger?
The classes you meet
- O(1): constant. Reading an array element by index, looking up a key in a hash table.
- O(log n): grows slowly. Binary search, lookups in a balanced tree or an index.
- O(n): linear. Scanning a list once.
- O(n log n): typical for good sorting algorithms.
- O(n²): quadratic. A loop inside a loop over the same data.
- O(2ⁿ): exponential. Fine only for tiny inputs.
Accidental quadratic code
The most common real-world problem is a hidden nested loop, such as searching a list inside a loop.
items = list(range(5000))
wanted = list(range(0, 5000, 7))
# O(n * m): each membership test scans the list.
slow = [x for x in wanted if x in items]
# O(n + m): build a set once, then each lookup is O(1).
lookup = set(items)
fast = [x for x in wanted if x in lookup]
print(slow == fast)With 5,000 items the difference is small, with five million it is the difference between a second and an hour. Database equivalents are the N+1 query pattern and a missing index causing full table scans.
Space matters too
Big-O applies to memory as well. A cache or a precomputed table trades space for time. Loading a whole file to process it line by line is O(n) memory where streaming is O(1).
Do not stop at Big-O
- Constants and caches matter. An O(n) scan over contiguous memory can beat an O(log n) structure for small n.
- Measure first. Profile before optimising, and optimise the part that is actually slow.
- Input size decides. For ten items almost anything works. Think about complexity where data can grow, such as user content and logs.
A quick way to estimate
Count the nested loops over the data, and ask what happens at ten times more data. Doubling the input and watching the running time is a cheap experiment.
Takeaway
Know the common classes, watch for hidden nested work, prefer hash lookups and indexes for searching, and verify with measurements.
Comments