Algorithms & Data Structures for AI
Not "pure math," but every AI/ML interview loop tests this alongside the theory — and understanding complexity is what lets you reason about whether an ML system will actually scale.
Intuition: Complexity Classes Aren't Academic — They're a Budget
Every number on this page is really answering one question: as a real input (a sequence, a vocabulary, a dataset) grows, does the cost grow slowly enough to still be affordable? and look similar on paper; at real production scale they're the difference between "fine" and "the reason this system can't ship." That gap, made concrete with real operation counts rather than asymptotic notation alone, is what this page is really about.
Big-O Complexity
Big-O describes how an algorithm's running time (or memory) grows as input size grows, ignoring constant factors. Drag and watch real operation counts diverge:
- — constant time (hash map lookup)
- — logarithmic (binary search, balanced tree operations)
- — linear (scanning a list once)
- — the cost of efficient sorting, and many "divide and conquer" algorithms
- — quadratic (naive pairwise comparison — e.g. computing full pairwise attention scores)
- — exponential (brute-force search over subsets — avoid at all costs)
Why this matters for AI specifically: self-attention is in sequence length, which is why long-context LLMs are hard and expensive, and why Flash Attention / sparse attention exist — direct responses to this complexity bound, made concrete below.
Core Data Structures
- Arrays — contiguous memory, index access. Tensors are just multi-dimensional arrays.
- Hash maps — average insert/lookup via hashing. Used for tokenizer vocabularies, caching, and de-duplication in data pipelines. Real op-count comparison against the naive alternative:
- Trees — hierarchical structure. Decision trees are this data structure directly; balanced trees (B-trees) underlie database indexes.
- Graphs — nodes + edges. Directly relevant to graph databases (Neo4j), GraphRAG, and modeling multi-agent communication topology.
- Heaps / priority queues — efficiently retrieve the min/max element. Used in beam search (keeping the top- candidate sequences during LLM decoding) and in Dijkstra-style search algorithms. Real beam search, real cumulative log-probabilities, real top-k pruning at every step:
Sorting & Searching
Sorting ( for comparison-based sorts like merge sort/quicksort) shows up whenever you rank candidates — e.g. sorting retrieved documents by relevance score in a RAG pipeline, or ranking recommendations. Real comparison counts, not just the asymptotic label:
Binary search () requires sorted data, used in efficient lookup structures. Approximate Nearest Neighbor search (HNSW, IVF — covered in Databases) is the vector-database analog of search, trading exactness for speed at scale.
Complexity of Common ML Algorithms
| Algorithm | Training complexity (roughly) | Notes |
|---|---|---|
| k-Nearest Neighbors | train, per query (naive) | No real "training" — all cost is at inference |
| k-Means | clusters, iterations | |
| Decision Tree | features | |
| Matrix multiply (a layer's forward pass) | For an by multiply | |
| Self-attention | = sequence length, = embedding dim — the scaling bottleneck for LLMs |
Real operation counts for self-attention's against a linear-attention alternative, at real sequence lengths:
Knowing these numbers is what lets you answer "why is this slow, and what would make it faster" — a staple of both ML system design interviews and real production debugging.
Code: The Beam Search Loop, For Real
The exact algorithm the diagram above steps through:
Why this belongs in a math curriculum
Interviewers (and real jobs) expect ML engineers to be comfortable with general software engineering fundamentals, not just theory — see Interview Prep for how this gets tested directly. But it also isn't separable from the math: understanding why attention is expensive, why vector search needs approximate algorithms, and why certain training loops scale better than others all comes back to Big-O reasoning applied to the linear algebra operations covered on the Linear Algebra page.
Mathematics for AI complete. Next: Machine Learning — where this math turns into working algorithms.