Big O & Complexity Analysis
Why it matters
Big O describes how the time (or memory) of an algorithm grows as the input gets bigger. It lets you compare solutions before you write them.
Common classes (fastest to slowest)
| Big O | Name | Example | 1,000,000 items |
|---|---|---|---|
| O(1) | constant | dict lookup, list[i] | 1 step |
| O(log n) | logarithmic | binary search | ~20 steps |
| O(n) | linear | loop over a list | 1,000,000 |
| O(n log n) | linearithmic | sorted() | ~20,000,000 |
| O(n²) | quadratic | two nested loops | 10¹² 😱 |
How to estimate
- Drop constants:
2n + 5→ O(n). - Keep the biggest term:
n² + n→ O(n²). - Nested loops multiply; loops one after another add.
Python costs to remember
| Operation | Cost |
|---|---|
x in list | O(n) |
x in set / x in dict | O(1) average |
list.append | O(1) |
list.insert(0, x) / list.pop(0) | O(n), so use collections.deque |
▶️ Runs in the app.
Example
import time
def linear_search(items, target): # O(n)
for i, value in enumerate(items):
if value == target:
return i
return -1
def binary_search(items, target): # O(log n), items must be sorted
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
data = list(range(1_000_000))
for fn in (linear_search, binary_search):
start = time.perf_counter()
fn(data, 999_999)
print(f"{fn.__name__}: {time.perf_counter() - start:.6f}s")
# list vs set membership
as_set = set(data)
print(999_999 in as_set) # instant: O(1)