Big O: Time and Space Complexity

Big O notation describes the asymptotic upper bound on how an algorithm's time or memory usage grows with input size, requiring clear specification of worst-case, average-case, or amortized regimes.

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 n=106n=10^6, an O(nlog⁡n)O(n\log n) algorithm performs roughly 2×1072\times 10^7 operations, whereas an O(n2)O(n^2) algorithm requires 101210^{12} operations—often the difference between milliseconds and hours.
  • Choosing the right data structure: Membership lookup in a list is O(n)O(n), whereas lookup in a set or dict is average-case O(1)O(1) (see k2.ds.hash-table).
  • Understanding LLM compute scaling: Standard dense self-attention scales quadratically—O(n2)O(n^2)—with sequence length nn.

Boundaries & Caveats

Writing O(n2)O(n^2) specifies an upper bound and does not guarantee that doubling nn 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: f(n)=O(g(n))f(n) = O(g(n)) if and only if there exist constants c>0c>0 and n0n_0 such that f(n)≤c⋅g(n)f(n) \le c \cdot g(n) for all n≥n0n \ge n_0:

f(n)=O(g(n))  ⟺  ∃ c>0, n0, ∀n≥n0: f(n)≤c g(n) f(n) = O(g(n)) \iff \exists\, c>0,\ n_0,\ \forall n \ge n_0:\ f(n) \le c\, g(n)

For example, 3n2+5n+100=O(n2)3n^2 + 5n + 100 = O(n^2) because as nn grows large, the n2n^2 term dominates all lower-order terms.

Figure 1
Complexity Name Typical Examples
O(1)O(1) Constant Array index access, hash table lookup
O(log⁡n)O(\log n) Logarithmic Binary search, balanced BST operations
O(n)O(n) Linear Single pass traversal, linear scan
O(nlog⁡n)O(n \log n) Linearithmic Merge sort, Quicksort (average case)
O(n2)O(n^2) Quadratic Bubble sort, nested pairwise loops, dense self-attention
O(2n)O(2^n) 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 nn 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 nn roughly doubles the runtime for O(n)O(n) and O(nlog⁡n)O(n\log n), and quadruples (~4.5×) the runtime for O(n2)O(n^2).
  • The sub-1.0 ratio on the O(1)O(1) 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 162=256×16^2 = 256\times.

Common Pitfalls

  • Assuming a lower Big O class is always faster at every input size: Constant factors and cache locality matter. At very small nn, O(n2)O(n^2) insertion sort beats O(nlog⁡n)O(n\log n) sorts (which is why Python's Timsort uses binary insertion sort on short runs).
  • Ignoring worst-case complexity: Quicksort averages O(nlog⁡n)O(n\log n) but degrades to O(n2)O(n^2) on adversarial pivots (see k2.algo.quicksort).
  • Conflating average, worst-case, and amortized bounds: list.append is amortized O(1)O(1), even though an individual resize step copies O(n)O(n) references.
  • Checking time complexity while ignoring space complexity: Merge sort guarantees O(nlog⁡n)O(n\log n) time but allocates O(n)O(n) 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 O(n)O(n) pass into O(n2)O(n^2).

Connection to AI Development

  • Quadratic self-attention cost: Standard self-attention computes an n×nn\times n attention matrix in O(n2d)O(n^2 d) FLOPs. FlashAttention keeps the same O(n2d)O(n^2 d) FLOP order but tiles the computation in SRAM so the full n×nn\times n matrix is never materialized in HBM, cutting memory footprint to O(n)O(n): https://arxiv.org/abs/2205.14135
  • Vector retrieval: Exact brute-force k-NN search costs O(Nd)O(Nd) 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 O(n2)O(n^2) pairwise similarity loop is infeasible and must be replaced with hashing or LSH/MinHash bucketing.

Further Reading

Comprehension Check

Mathematically, is an O(n)O(n) algorithm also in O(n2)O(n^2)?

Reference answer: Yes. Big O specifies an asymptotic upper bound; to express a tight upper-and-lower asymptotic growth rate, use Big Theta (Θ\Theta).

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Run log: 18_big_o.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram