Sub topic 5
The Common Complexity Classes from O(1) to O(n!)
This chapter assumes you can read Python loops and recursion, know what an array is, and are comfortable with exponents. A rough grasp of logarithms helps. Here, log n means the number of times you can halve n before reaching 1. Earlier chapters showed how to drop constants and lower-order terms. This chapter names the classes you will meet most often and shows what code produces each one.
The ladder of classes
Most algorithms fall into a small set of classes. They are listed here from slowest-growing to fastest-growing.
| Class | Name | Typical source |
|---|---|---|
| O(1) | Constant | Index into an array |
| O(log n) | Logarithmic | Halving the search range each step |
| O(n) | Linear | One pass over the input |
| O(n log n) | Linearithmic | Divide and conquer with a linear merge |
| O(n^2) | Quadratic | Nested loops over the input |
| O(2^n) | Exponential | Branching recursion with two calls per level |
| O(n!) | Factorial | Trying every ordering of n items |
The ordering holds for large n. For any fixed power, n^k eventually beats log n, and 2^n eventually beats every n^k.
Constant, linear, and quadratic
The first example from the plan shows the three simplest classes.
def first_item(items):
return items[0] # O(1): one step regardless of len(items)
def total(items):
s = 0
for x in items: # runs n times
s += x
return s # O(n)
def has_duplicate(items):
n = len(items)
for i in range(n):
for j in range(i + 1, n):
if items[i] == items[j]:
return True
return False # worst case n(n-1)/2 comparisons, which is O(n^2)first_item does the same work for any input length. total does one addition per element. has_duplicate compares each pair once. That is n(n-1)/2 = n^2/2 - n/2 comparisons. Dropping the constant 1/2 and the lower-order term leaves O(n^2).
Logarithmic time
A loop is logarithmic when each step shrinks the remaining work by a constant factor. Binary search is the standard case.
def binary_search(sorted_items, target):
lo, hi = 0, len(sorted_items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sorted_items[mid] == target:
return mid
if sorted_items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Each iteration halves the range, so the loop runs at most about log2(n) + 1 times. For n = 1,000,000 that is about 21 iterations. The base of the logarithm does not matter in Big O, because changing the base only multiplies by a constant.
Linearithmic time
O(n log n) appears when you do linear work at each of about log n levels. Merge sort splits the list in half repeatedly, which gives log n levels. Merging at each level touches all n elements. Comparison-based sorting cannot do better than this in the worst case, so it is a common target.
Exponential and factorial time
Exponential growth comes from recursion that branches without reusing results.
def fib_naive(n):
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)Each call makes two more calls, so the number of calls is bounded by O(2^n). Adding 1 to n roughly doubles the work. Caching results (memoization) brings this to O(n), which is why the same problem can sit in very different classes.
Factorial growth comes from enumerating permutations. Three items have 6 orderings, ten items have 3,628,800, and twenty items have more than 2 x 10^18. Brute-force solutions to the traveling salesman problem work this way.
How fast the classes diverge
The table shows approximate operation counts.
| n | log n | n log n | n^2 | 2^n |
|---|---|---|---|---|
| 10 | 3 | 33 | 100 | 1,024 |
| 100 | 7 | 664 | 10,000 | about 1.3 x 10^30 |
| 1,000 | 10 | 9,966 | 1,000,000 | about 10^301 |
Exercise
What is the time complexity of this function, and why? def count_pairs(items): n = len(items) k = 1 count = 0 while k < n: for x in items: count += 1 k *= 2 return count
Show answer
O(n log n). The while loop doubles k each pass, so it runs about log2(n) times. The inner for loop runs n times on every pass. The total is n * log n operations.
Exercise
A brute-force algorithm tries every ordering of 12 items. Roughly how many orderings does it check, and what class is this?
Show answer
12! = 479,001,600 orderings, which is factorial time, O(n!).