Python · Module 12 · Lesson 11 min read

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 ONameExample1,000,000 items
O(1)constantdict lookup, list[i]1 step
O(log n)logarithmicbinary search~20 steps
O(n)linearloop over a list1,000,000
O(n log n)linearithmicsorted()~20,000,000
O(n²)quadratictwo nested loops10¹² 😱

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

OperationCost
x in listO(n)
x in set / x in dictO(1) average
list.appendO(1)
list.insert(0, x) / list.pop(0)O(n), so use collections.deque

▶️ Runs in the app.

Example

Python
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)