Measuring Cost Precisely
Complexity analysis predicts how an algorithm's time (operations) and space (memory) grow with input size without running code.
The tool is asymptotic notation, which ignores constants and lower-order terms to focus on scaling behavior for large inputs:
| Notation | Bound Type | Meaning |
|---|---|---|
| Big-O () | Upper bound | Grows at most this fast |
| Big-Omega () | Lower bound | Grows at least this fast |
| Big-Theta () | Tight bound | Grows exactly this fast |
Count dominant operations: a loop is , nested loops are , halving is , and fixed work is .
Common pitfall: Writing ''. Drop constants and lower terms: it is simply , because the dominant term alone captures scale.
Cases and Space
Costs depend heavily on case: the worst case bounds maximum slowness, the average case reflects typical inputs, and the best case is usually uninformative.
Space complexity measures memory. Algorithms often feature a space-time trade-off: merge sort takes time but extra space, while heapsort sorts in place with space.
Quick Rules:
- Only the fastest-growing term matters: simplifies to .
- Quicksort is average but worst case.
- Always evaluate both time and memory constraints before selecting an algorithm for large datasets.