Sub topic 5
The Common Complexity Classes from O(1) to O(n!)
This chapter assumes you can read Python, know what a loop and a recursive call are, and are comfortable with exponents. It also assumes you have seen the idea of Big O as an upper bound on growth. Here we name the handful of growth rates that appear in nearly every algorithm, show what code produces each one, and give you a feel for how far apart they are.
Why a short list is enough
Once you drop constant factors and lower-order terms, the cost of most algorithms falls into a small set of shapes. A function like 3n^2 + 5n + 7 becomes O(n^2). Many different programs share that label. Learning the list lets you spot the class from the structure of the code, and compare two algorithms by looking at where each sits on the list.
The classes below are ordered from slowest-growing to fastest-growing. If f appears before g in this order, then for large enough n the cost f(n) is smaller than g(n).
The classes one by one
O(1): constant time
The number of steps does not depend on the input size. Indexing into a list, reading a dictionary entry by key, and pushing onto a stack are typical.
def first_item(items):
return items[0] # one step, however long items is"Constant" does not mean "fast" or "one step". It means the cost has a ceiling that does not move as n grows. A function that always does 1,000 operations is still O(1).
O(log n): logarithmic time
Each step removes a constant fraction of the remaining work, usually half. 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 -1The loop runs at most about log2(n) + 1 times. For one million items that is about 20 iterations. For one billion it is about 30.
The base of the logarithm does not matter inside Big O. log10(n) and log2(n) differ only by a constant factor (log2(n) = log2(10) * log10(n)), and constants are dropped. So you write O(log n) without a base.
O(n): linear time
The work is proportional to the input size, because you touch each element a constant number of times.
def total(items):
s = 0
for x in items: # runs n times
s += x
return sFinding a maximum, counting matches, and copying a list are all O(n). Any algorithm that must look at every input element is at least linear.
O(n log n): linearithmic time
This is a linear amount of work repeated across about log n levels. It is the cost of efficient comparison sorts such as merge sort, and of Python's built-in sorted().
The merge sort code from the spine splits the list in half, sorts each half, then merges in linear time. That gives about log2(n) levels of splitting with O(n) merge work at each level. Later chapters derive this formally with a recurrence. For now, remember that O(n log n) grows only slightly faster than O(n) and far slower than O(n^2).
O(n^2) and O(n^3): polynomial time
Quadratic time typically comes from comparing every pair of elements. Cubic time comes from every triple, or from three nested loops.
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)The classic cubic example is the textbook method for multiplying two n x n matrices: for each of n^2 output cells, sum n products. Quadratic algorithms are fine for thousands of items. They become painful at millions.
O(2^n): exponential time
The work doubles whenever the input grows by one element. This happens when you examine every subset of a set, or when a recursive function makes two calls on a problem that shrinks only by one.
def all_subsets(items):
subsets = [[]]
for x in items:
subsets += [s + [x] for s in subsets] # every existing subset, with and without x
return subsets
print(len(all_subsets([1, 2, 3]))) # 8
print(len(all_subsets(list(range(20))))) # 1048576A set of n items has exactly 2^n subsets. No algorithm that must produce them all can do better than O(2^n), since the output alone has that size.
The naive fib_naive from the spine is another exponential case. Its call count is bounded by O(2^n). The true growth rate is slightly smaller, near 1.618^n, but it is still exponential.
O(n!): factorial time
Factorial growth appears when you try every ordering of n items. There are n * (n-1) * ... * 1 permutations.
from itertools import permutations
def count_orderings(items):
return sum(1 for _ in permutations(items))
print(count_orderings([1, 2, 3, 4])) # 24
print(count_orderings(list(range(8)))) # 40320Brute-force solutions to the traveling salesman problem work this way: they test every route. Factorial algorithms are unusable beyond roughly n = 10 to n = 12.
How far apart the classes are
The table shows approximate operation counts. Logarithms are base 2.
| Class | n = 10 | n = 20 | n = 100 |
|---|---|---|---|
| O(1) | 1 | 1 | 1 |
| O(log n) | 3.3 | 4.3 | 6.6 |
| O(n) | 10 | 20 | 100 |
| O(n log n) | 33 | 86 | 664 |
| O(n^2) | 100 | 400 | 10,000 |
| O(n^3) | 1,000 | 8,000 | 1,000,000 |
| O(2^n) | 1,024 | 1,048,576 | about 1.3 x 10^30 |
| O(n!) | 3,628,800 | about 2.4 x 10^18 | about 9.3 x 10^157 |
Two things stand out. First, the polynomial rows stay manageable even at n = 100. Second, the last two rows leave the realm of computation. At n = 100, 2^n is already more operations than any computer could perform in the age of the universe.
A common rule of thumb for a machine doing about 10^8 to 10^9 simple operations per second:
O(n)andO(n log n)handle inputs of millions or tens of millions.O(n^2)handles inputs up to roughly tens of thousands.O(n^3)handles inputs of a few hundred to a thousand or so.O(2^n)handlesnup to about 25 to 30.O(n!)handlesnup to about 10 to 12.
These figures are estimates, not guarantees. They are useful for deciding quickly whether an approach is plausible before you write it.
Reading the class from the code
You can often guess the class from the shape of the code before counting anything precisely:
- A fixed number of operations with no loop over the input suggests
O(1). - A loop whose remaining range is halved (or multiplied by a constant) each pass suggests
O(log n). - One pass over the input suggests
O(n). - A linear pass inside a halving structure, or a sort, suggests
O(n log n). - Two nested passes over the input suggest
O(n^2). Three suggestO(n^3). - Branching recursion that shrinks the problem by a constant per call suggests
O(2^n). - Trying all orderings suggests
O(n!).
The next chapter turns the loop rules into a systematic method.
Common mistakes
- Treating O(1) as always faster. A constant-time operation with a large constant can lose to a logarithmic one for realistic inputs. Big O ignores constants on purpose.
- Confusing
n log nwithlog n. Sorting a list is far more expensive than searching it. The two are not interchangeable. - Calling every recursion exponential. Recursion with one call per level, or with two calls on halves plus linear work, is polynomial or linearithmic. Branching alone does not make it exponential. The shrink rate of the subproblems matters.
- Mixing up
2^nandn^2. Atn = 20,n^2is 400 and2^nis over a million. The variable in the exponent is the whole difference. - Assuming the output size is free. An algorithm that returns all
2^nsubsets cannot beatO(2^n), since writing the output takes that long.
Exercise
A function receives a list of n distinct numbers and returns every ordered pair (a, b) of different elements, as a list. What is its time complexity, and why can no implementation do better?
Show answer
There are n * (n - 1) ordered pairs, which simplifies to O(n^2). Any correct implementation must produce all of them, so writing the output already takes O(n^2) time. The lower bound comes from the output size.
Exercise
You have an algorithm that takes about 1 second for n = 30 and has time complexity O(2^n). Roughly how long would it take for n = 40, assuming the constant factor stays the same? Would an O(n^2) algorithm that takes 1 second at n = 30 have the same trouble?
Show answer
Going from n = 30 to n = 40 multiplies the work by 2^10 = 1024, so it takes about 1024 seconds, roughly 17 minutes. The O(n^2) algorithm would grow by (40/30)^2, about 1.8, so it would take about 1.8 seconds. The exponential algorithm gets much slower for a small increase in n, while the polynomial one does not.