Sub topic 2
The Common Complexity Classes from O(1) to O(n!)
Assume you know variables, loops, functions, arrays, basic algebra, and recursion. This chapter uses time complexity, which describes how an algorithm’s work grows as input size n grows. It does not predict exact seconds.
Common growth rates
From slowest growth to fastest:
| Complexity | Typical example | Growth |
|---|---|---|
| `O(1)` | Reading `items[0]` | Constant |
| `O(log n)` | Binary search | Logarithmic |
| `O(n)` | Scanning a list | Linear |
| `O(n log n)` | Merge sort | Linearithmic |
| `O(n²)` | Comparing every pair | Quadratic |
| `O(2ⁿ)` | Naive recursive Fibonacci | Exponential |
| `O(n!)` | Trying every permutation | Factorial |
An O(1) operation takes about the same number of steps for any input size. An O(n) operation grows in direct proportion to n. Exponential and factorial algorithms become impractical quickly.
Reading loops and nested loops
Count how many times each operation can run.
def total(items):
result = 0
for value in items: # n iterations
result += value
return result # O(n)
def compare_pairs(items):
for i in range(len(items)):
for j in range(i + 1, len(items)):
if items[i] == items[j]:
return True
return False # O(n²)Sequential loops usually add their costs. O(n) + O(n) simplifies to O(n). Nested loops usually multiply their costs, producing O(n²) here.
A loop that halves its remaining work each time is logarithmic. Binary search is O(log n) because each comparison discards half the search range.
Big Omega and Big Theta
Big O gives an asymptotic upper bound: beyond some input size, the algorithm takes no more than a constant multiple of the stated function.
Big Omega, written Ω, gives a lower bound. Big Theta, written Θ, gives a tight bound when both the upper and lower bounds have the same growth.
For a list scan:
- Best case:
Ω(1)if the target is first. - Worst case:
O(n)if the target is last or absent. - Tight worst-case bound:
Θ(n).
Best, worst, and average case
The best case is the most favorable input. The worst case is the least favorable. The average case estimates typical cost under an assumed input distribution.
These labels describe inputs, while O, Ω, and Θ describe bounds. Do not call every result “Big O” without stating which case you analyzed.
Exercise
What is the worst-case time complexity of two sequential loops, each scanning all n items?
Show answer
O(n). Their costs add: O(n) + O(n) = O(2n), which simplifies to O(n).