Big-O Notation
Big-O notation describes the asymptotic upper bound of a function's growth rate. It's how we compare algorithm efficiency without caring about constants or hardware.
Formal definition
We say if there exist positive constants and such that:
In plain English: grows at most as fast as , up to a constant factor, for sufficiently large .
Common complexity classes
| Notation | Name | Example |
|---|---|---|
| Constant | Array index access | |
| Logarithmic | Binary search | |
| Linear | Linear search | |
| Linearithmic | Merge sort, heap sort | |
| Quadratic | Bubble sort, naive matrix mult. | |
| Cubic | Standard matrix multiplication | |
| Exponential | Brute-force subset enumeration | |
| Factorial | Naive traveling salesman |
Example: linear search
def linear_search(arr, target):
for i, x in enumerate(arr):
if x == target:
return i
return -1
The loop runs at most times, so this is .
Example: binary search
def binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
Each iteration halves the search space, so it takes time.
warning
Big-O describes the worst case. Big-Θ (theta) describes a tight bound; Big-Ω (omega) describes a lower bound. Don't conflate them.
Related
- Vectors — linear algebra cost analysis often uses these bounds.