Loading
Loading
Complexity Analysis
The notation itself: what it means, what it discards, and how to read it correctly.
By the end of this chapter
Writing O(n²) says: beyond some input size, this algorithm's cost is at most a constant multiple of n². It is an upper bound on the growth rate, nothing more.
Two things are thrown away, and knowing which two makes the notation easy to apply.
T(n) = 4n² + 30n + 9004n² + 30n + 900the raw operation countn² + n + 1drop the constant multipliersn²keep only the fastest-growing termO(n²)| Notation | Name | n = 1,000 costs roughly |
|---|---|---|
| O(1) | Constant | 1 |
| O(log n) | Logarithmic | 10 |
| O(n) | Linear | 1,000 |
| O(n log n) | Linearithmic | 10,000 |
| O(n²) | Quadratic | 1,000,000 |
| O(2ⁿ) | Exponential | more than atoms in the observable universe |
The same algorithm can have three different answers depending on which input you consider.
def find(nums, target): for i, value in enumerate(nums): if value == target: return i return -1When someone says this is O(n) without qualification, they mean the worst case. That is the convention, because the worst case is the only one you can promise.
Quick quiz
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for:
Before moving on: take the quiz above.