One-Sentence Definition
Big O notation gives an asymptotic upper bound on how an algorithm's time or memory consumption scales as input size grows—helping compare scalability while distinguishing worst-case, average-case, and amortized guarantees across input parameters.
Why It Matters
- Predicting whether a job will finish: At , an algorithm performs roughly operations, whereas an algorithm requires operations—often the difference between milliseconds and hours.
- Choosing the right data structure: Membership lookup in a
listis , whereas lookup in asetordictis average-case (see k2.ds.hash-table). - Understanding LLM compute scaling: Standard dense self-attention scales quadratically——with sequence length .
Boundaries & Caveats
Writing specifies an upper bound and does not guarantee that doubling always multiplies wall-clock runtime by exactly 4; the 4× ratio holds approximately when the quadratic term dominates and constant factors remain stable. Real-world wall time also depends on cache locality, vectorization, hardware bandwidth, and I/O.
How It Works / Diagram
Formal definition: if and only if there exist constants and such that for all :
For example, because as grows large, the term dominates all lower-order terms.
| Complexity | Name | Typical Examples |
|---|---|---|
| Constant | Array index access, hash table lookup | |
| Logarithmic | Binary search, balanced BST operations | |
| Linear | Single pass traversal, linear scan | |
| Linearithmic | Merge sort, Quicksort (average case) | |
| Quadratic | Bubble sort, nested pairwise loops, dense self-attention | |
| Exponential | Unmemoized recursive Fibonacci, subset enumeration |
Time complexity reference for built-in Python containers: https://wiki.python.org/moin/TimeComplexity
Runnable Example
A doubling experiment: double input size and measure the runtime ratio across complexity classes, then print growth tables and Transformer attention matrix element counts (recorded run on Python 3.15.0):
# File: examples/18_big_o.py
# Big O: how does runtime scale when input size doubles? Empirical doubling test
import time, bisect
def timed(fn, n, reps=3):
best = float("inf")
for _ in range(reps):
t0 = time.perf_counter(); fn(n); best = min(best, time.perf_counter() - t0)
return best
data = {}
def o1(n): return data.get(n) # O(1)
def ologn(n): arr = range(n); return bisect.bisect_left(arr, n // 3) # O(log n)
def on(n): return sum(range(n)) # O(n)
def onlogn(n): return sorted(range(n, 0, -1)) # O(n log n) (reverse-sorted input)
def on2(n): return sum(1 for i in range(n) for j in range(n)) # O(n^2)
print(f"{'Complexity':<10}{'n=base':>12}{'n=2*base':>12}{'Ratio':>8}")
for name, fn, n in [("O(1)", o1, 1000), ("O(log n)", ologn, 1000), ("O(n)", on, 200_000),
("O(n log n)", onlogn, 200_000), ("O(n^2)", on2, 1000)]:
t1, t2 = timed(fn, n), timed(fn, 2 * n)
print(f"{name:<10}{t1*1e6:>10.1f}µs{t2*1e6:>10.1f}µs{t2/t1:>8.1f}")
print("Theoretical ratios: O(1)≈1, O(log n)≈1.1, O(n)≈2, O(n log n)≈2.1, O(n^2)≈4 (empirical runs vary with cache & constants)")
# Growth rate table
import math
print(f"\n{'n':>8}{'log n':>8}{'n log n':>12}{'n^2':>16}{'2^n':>12}")
for n in [10, 100, 1000, 10**6]:
two = f"{2**n:.1e}" if n <= 1000 else "astronomical"
print(f"{n:>8}{math.log2(n):>8.1f}{n*math.log2(n):>12.0f}{n*n:>16.0e}{two:>12}")
# Transformer self-attention: O(L^2) attention score matrix size for context length L
for L in [1024, 8192, 131072]:
print(f"Context {L:>6} tokens: attention score matrix has {L*L:>17,} elements")
Recorded output:
Complexity n=base n=2*base Ratio
O(1) 0.2µs 0.1µs 0.4
O(log n) 0.6µs 0.5µs 0.9
O(n) 1340.9µs 2682.0µs 2.0
O(n log n) 4529.8µs 9274.3µs 2.0
O(n^2) 13563.7µs 61019.6µs 4.5
Theoretical ratios: O(1)≈1, O(log n)≈1.1, O(n)≈2, O(n log n)≈2.1, O(n^2)≈4 (empirical runs vary with cache & constants)
n log n n log n n^2 2^n
10 3.3 33 1e+02 1.0e+03
100 6.6 664 1e+04 1.3e+30
1000 10.0 9966 1e+06 1.1e+301
1000000 19.9 19931569 1e+12 astronomical
Context 1024 tokens: attention score matrix has 1,048,576 elements
Context 8192 tokens: attention score matrix has 67,108,864 elements
Context 131072 tokens: attention score matrix has 17,179,869,184 elements
- Doubling roughly doubles the runtime for and , and quadruples (~4.5×) the runtime for .
- The sub-1.0 ratio on the row illustrates measurement noise at sub-microsecond durations where timer overhead dominates.
- Scaling context length 16× from 8K to 128K increases the attention score matrix size by .
Common Pitfalls
- Assuming a lower Big O class is always faster at every input size: Constant factors and cache locality matter. At very small , insertion sort beats sorts (which is why Python's Timsort uses binary insertion sort on short runs).
- Ignoring worst-case complexity: Quicksort averages but degrades to on adversarial pivots (see k2.algo.quicksort).
- Conflating average, worst-case, and amortized bounds:
list.appendis amortized , even though an individual resize step copies references. - Checking time complexity while ignoring space complexity: Merge sort guarantees time but allocates auxiliary memory.
- Overlooking hidden inner loops: Calling
x in my_list,my_list.index(x), or repeated string concatenation inside a loop can silently turn an pass into .
Connection to AI Development
- Quadratic self-attention cost: Standard self-attention computes an attention matrix in FLOPs. FlashAttention keeps the same FLOP order but tiles the computation in SRAM so the full matrix is never materialized in HBM, cutting memory footprint to : https://arxiv.org/abs/2205.14135
- Vector retrieval: Exact brute-force k-NN search costs per query, whereas approximate nearest-neighbor (ANN) indexes like HNSW reduce query time to empirical sub-linear scaling.
- Corpus deduplication pipelines: On a 10-million-document corpus, an pairwise similarity loop is infeasible and must be replaced with hashing or LSH/MinHash bucketing.
Further Reading
- Python Wiki – TimeComplexity: https://wiki.python.org/moin/TimeComplexity
- Big-O Cheat Sheet: https://www.bigocheatsheet.com/
- Wikipedia – Big O notation: https://en.wikipedia.org/wiki/Big_O_notation
Comprehension Check
Mathematically, is an algorithm also in ?
Reference answer: Yes. Big O specifies an asymptotic upper bound; to express a tight upper-and-lower asymptotic growth rate, use Big Theta ().
Verification & Reproduction
Verified on: 2026-10-14. Example status: Passed. Run log: 18_big_o.py.
Companion Code & Verification Materials