Big-O and Complexity Analysis

2 min read

Big-O notation describes how an algorithm's time or space scales with input size nn, ignoring constants and lower-order terms.

Common classes (fastest to slowest):

ClassNameExample in ML
O(1)O(1)ConstantHash table lookup, embedding index
O(logn)O(\log n)LogarithmicBinary search for threshold tuning
O(n)O(n)LinearSingle pass over dataset, forward pass of one layer
O(nlogn)O(n \log n)LinearithmicSorting logits for top-kk, FFT in signal processing
O(n2)O(n^2)QuadraticSelf-attention over sequence length nn
O(n3)O(n^3)CubicNaive matrix multiply, SVD of n×nn \times n matrix
O(2n)O(2^n)ExponentialBrute-force search over all subsets

Space complexity matters too: storing all attention scores takes O(n2)O(n^2) memory. FlashAttention reduces this to O(n)O(n) by recomputation.

Amortized analysis: some operations are expensive occasionally but cheap on average. Example: appending to a dynamic array is O(1)O(1) amortized despite occasional O(n)O(n) resizes. KV-cache growth in autoregressive generation follows a similar pattern.

What to internalize:

  • A dense layer on RnRm\mathbb{R}^n \to \mathbb{R}^m costs O(nm)O(nm) FLOPs
  • Self-attention is O(n2d)O(n^2 d) where nn = sequence length, dd = head dimension
  • Knowing complexity tells you what will break at scale — if it's O(n2)O(n^2), doubling nn quadruples cost
  • Constants matter in practice: O(n2)O(n^2) with small constant can beat O(nlogn)O(n \log n) with large constant for realistic nn

See also: Computational Complexity of Attention, P vs NP and Intractability

Linked from