1.Big-O, time complexity, and space complexity
Big-O describes how an algorithm's cost grows as input size grows, ignoring constant factors. Time complexity measures growth in operations; space complexity measures growth in memory — both are about the SHAPE of growth.
Key features
- O(1): constant — cost does not grow with input size (dict/set lookup)
- O(n): linear — cost grows proportionally with input size (scanning a list once)
- O(n²): quadratic — cost grows with the square of input size (comparing every pair)
- O(log n): logarithmic — cost grows very slowly as input grows (binary search)
- Big-O describes the WORST case by convention, ignoring constants — O(2n) is just O(n)
Common complexities, smallest to largest
- O(1): Small n, Cheap — dict[key], set membership — flat, always
- O(log n): between Small n and Large n, Cheap — binary search — grows very slowly
- O(n): between Small n and Large n, between Cheap and Expensive — a single loop over n items
- O(n log n): Large n, between Cheap and Expensive — sorted(), list.sort()
- O(n²): Large n, Expensive — nested loop — measured 584x slower at n=5000
Command
# O(1) dict[key], set membership
# O(n) for item in items: ...
# O(n log n) sorted(items)
# O(n^2) nested loop over the same collectionBig-O describes how cost grows with input size, not today's runtime — O(n) eventually beats O(n²), however tuned.