Every algorithm, data structure, theorem or construction known by a name (about 400, grouped by first letter; use the table of contents to jump), with what it does and where it lives in these notes. For “which algorithm solves which problem in what time”, see the 🐬 Complexity Cheat Sheet; for famous problems, see 🐬 Classic Problems.

A

NameWhat it doesNote
A* searchshortest path guided by an admissible heuristicInformed Search
Ackermann function (inverse α)the near-constant factor in DSU and MST boundsDisjoint Set Union
Adaptive Simpsonnumerical integration with Richardson correctionRoot Finding and Integration
AM–GM–HM inequalityarithmetic mean geometric mean harmonic mean, equality iff all terms equal🐬 Formula
Agrawal–Kayal–Saxena (AKS)first deterministic polynomial-time primality testTheoretical Algorithms Catalog
Aho–Corasick automatonmulti-pattern matching with suffix linksTrie and Aho–Corasick
Aho–Corasickmany-pattern matching with an automaton of failure linksTrie and Aho-Corasick
Aho–Hopcroft–Ullmanlinear-time rooted tree isomorphism (the AHU canonical labels)Tree Isomorphism and PrĂŒfer Codes
AHU encodingcanonical form of rooted trees, tree isomorphismTree Isomorphism
Ahuja–Orlinscaling max-flow and min-cost flow algorithmsTheoretical Algorithms Catalog
Aldous–Broderuniform random spanning tree by a random walkMatrix-Tree Theorem
Aliens trick (WQS binary search, Lagrangian relaxation)remove a “exactly ” constraint by penalisingAliens Trick
Andrew’s monotone chainconvex hull in Convex Hull
André’s reflection principlelattice paths with one or two boundariesCatalan and Lattice Paths
Apostolico–GiancarloBoyer–Moore variant with at most comparisonsTheoretical Algorithms Catalog
Appel–Haken (four colour theorem)every planar graph is 4-colourableSpecial Graph Classes
Arpa’s trickoffline RMQ with a DSU in per queryRange Minimum Query

B

NameWhat it doesNote
Baby-step giant-stepdiscrete logarithm in Discrete Log
Bernoulli’s inequality for , 🐬 Formula
Beatty’s theorem and partition the positive integersSprague–Grundy
BEST theoremcounts Eulerian circuits as arborescences times Euler Tours
Baeza-Yates–Gonnet (Shift-And / Shift-Or)bit-parallel string matching in Other Pattern Matching
Ballot problem (Bertrand)probability one candidate stays strictly ahead: Catalan Numbers and Lattice Paths
Banach–Knaster (last diminisher)proportional cake division for peopleCake Cutting
Barbier’s theoremevery curve of constant width has perimeter Buffon’s Needle
Bareiss algorithmfraction-free exact integer determinantDeterminants
Bareiss eliminationfraction-free integer determinantDeterminants and Permanents
Barnes–Hut approximate -body forces with a quadtreeKD-Tree and Spatial Structures
Barrett reductiondivision-free modular reduction for run-time moduliBarrett and Montgomery
Baum–WelchEM training of hidden Markov modelsDAG and Expected-Value DP
Bayes’ theoremProbability and Expectation
Bell triangleBell numbers in O(n^2)Stirling, Bell and Partitions
Bell triangle, Bell numbersnumber of set partitionsCounting Fundamentals
Bellman–Fordshortest paths with negative edges, negative-cycle detectionShortest Paths
Bellman–Held–Karpbitmask DP for TSP in Hamiltonian Paths and TSP
BenczĂșr–Kargergraph sparsification preserving all cutsGlobal Minimum Cut
Bender–Farach-Colton / LCA and RMQ via ±1 RMQRange Minimum Query
Bentley–Shamosdivide-and-conquer closest pair in Closest Pair
Berge’s theorema matching is maximum iff it has no augmenting pathBipartite Matching
Berkman–Vishkinparallel and linear-time RMQ / LCATheoretical Algorithms Catalog
Berlekamp’s algorithmdeterministic factorisation over small finite fieldsPolynomial Factorization
Berlekamp’s rule (Blue-Red stalks)value of a Hackenbush stalk from its colour sequenceHackenbush
Berlekamp–Massey algorithmshortest linear recurrence of a sequenceLinear Recurrences
Berlekamp–Masseyshortest linear recurrence of a sequenceLinear Recurrences
Bernstein–Nanongkai–Wulff-Nilsennear-linear negative-weight shortest pathsTheoretical Algorithms Catalog
Binet’s formulaclosed form Generating Functions
Birthday paradoxcollisions after random samplesProbability and Expectation
Bitap (shift-and)bit-parallel exact and approximate matchingOther Matching
Bitset (word-RAM) tricks-fold speedups of DP and set operationsBitset
Björklund’s hafnian algorithmweighted perfect matchings of a general graph in O(n^4 2^(n/2))Determinants
Björklund–Husfeldt–Koivistochromatic number / set cover in by inclusion–exclusionGraph Coloring
Bland’s ruleanti-cycling pivot rule for the simplex methodLinear Programming
Block-cut treetree of biconnected components and cut verticesBridges and Biconnectivity
Bloom filterset membership with false positives onlySampling and Streaming
Blossom (Edmonds)maximum matching in general graphsGeneral Matching
Bluestein (chirp-z)DFT of arbitrary length via convolutionConvolution Variants
Bluestein’s algorithmDFT of arbitrary length as a convolutionConvolution Variants
Boesch–Tindellwhich mixed graphs have a strongly connected orientationBridges and Biconnectivity
Bondy–Chvátal closureHamiltonicity via degree-sum closureHamiltonian Paths and TSP
Bonferroni inequalitiestruncated inclusion–exclusion gives alternating boundsInclusion–Exclusion
Booth / minimal rotationlexicographically least rotation in Lyndon Words
Booth’s algorithmleast rotation of a stringLyndon Words
BorĆŻvkaMST in , parallel-friendlyMST
Bose constructionSteiner triple system on points from an idempotent quasigroupKirkman’s Schoolgirls
Bose–Nelsonsorting networks for small Sorting, Selection and Inversions
Bostan–Mori algorithm[x^n] P/Q in O(k log k log n)Linear Recurrences
Bostan–Mori-th term of a linear recurrence in Linear Recurrences
Bouton’s theoremNim position is losing iff the XOR of heaps is 0Combinatorial Games and Nim
Bowyer–Watsonincremental Delaunay triangulationDelaunay and Voronoi
Boyer–Moore algorithmright-to-left matching with bad-character and good-suffix shiftsOther Matching
Boyer–Moore majority votemajority element in spaceClassic Array Problems
Boyer–Moore–GalilBoyer–Moore with a linear worst caseTheoretical Algorithms Catalog
Boyer–Moore–Horspoolsimplified Boyer–Moore with the bad-character rule onlyOther Pattern Matching
Boyer–Myrvoldlinear-time planarity testing and embeddingSpecial Graph Classes
Brent’s cycle detectioncycle detection with fewer evaluations than FloydFunctional Graphs
Brent–Kung compositionf(g(x)) by baby-step giant-stepComposition and Taylor Shift
Brent–Kungpower-series composition in Composition and Taylor Shift
Broken profile DPgrid tiling DP over a cell-by-cell frontierBroken Profile DP
Bron–Kerboschmaximal clique enumeration with pivotingMaximum Clique and Independent Set
Buffon’s needlecrossing probability ; Monte Carlo estimate of Buffon’s Needle
Burnside / PĂłlyacounting up to symmetryBurnside and PĂłlya
Burrows–Wheeler transformlast column of sorted rotations; FM-indexBurrows–Wheeler
Burrows–Wheeler transform, FM-indexcompression and pattern counting on a suffix-sorted stringBurrows-Wheeler
Buss kernelvertex cover kernel with at most kÂČ edgesComplexity Theory

C

NameWhat it doesNote
CarathĂ©odory’s theorema point in the convex hull of is in the hull of at most points of Convex Hull
Cantor–Zassenhaus algorithmrandomised factorisation over finite fieldsPolynomial Factorization
Cantor–Zassenhausrandomized factorization of polynomials over Polynomial Factorization
Carmichael numbers, Carmichael λFermat pseudoprimes to every base; the exponent of Primality Testing and Factorization
Cassini’s identityNumber Theory Miscellany
Catalan numbersbrackets, trees, triangulations, Dyck pathsCatalan and Lattice Paths
Cauchy–Binetdeterminant of a product of rectangular matricesMatrix-Tree Theorem
Cauchy–SchwarzGraph Basics and Modeling
Cayley’s formulan^(n-2) labelled trees, rooted forests k n^(n-k-1)Counting Graphs and Trees
Cayley’s formula, PrĂŒfer code labelled trees, tree sequence bijectionPrĂŒfer Codes
Cayley–Hamilton theorema matrix satisfies its characteristic polynomial; A^k via x^k mod chiCharacteristic Polynomial
Cayley–Hamiltona matrix satisfies its characteristic polynomialCharacteristic Polynomial
CDQ divide and conqueroffline 3D dominance / dynamic problemsCDQ
Centroid decompositionall-paths problems on trees in Centroid Decomposition
Chan’s algorithmoutput-sensitive convex hull in Convex Hull
Chazellelinear-time polygon triangulation; soft-heap MST in Theoretical Algorithms Catalog
Chebyshev distance; rotate 45° to turn it into ManhattanAttacking a Problem
Chen–Fox–Lyndon theoremunique factorization of a string into non-increasing Lyndon wordsLyndon Words and Minimal Rotation
Chernoff–Hoeffding boundsexponential tail bounds for sums of independent variablesProbability and Expectation
Chinese remainder theorem, Garnercombine congruencesCRT
Chirp-z transformevaluation at a geometric progression / DFT of any lengthConvolution Variants
Christofides3/2-approximation for metric TSP: MST + min matching on odd vertices + Euler tourApproximation Algorithms
Chtholly tree (ODT)assign-heavy interval maps on random dataChtholly Tree
Chu–Liu–Edmondsminimum arborescence (directed MST)Directed MST
Church–Turing thesisevery effective procedure is a Turing machineComplexity Theory and NP-Hardness
Cipolla, Tonelli–Shanksmodular square rootsModular Square Roots
Cocke–Younger–Kasami (CYK) context-free parsing by interval DPInterval DP
Coffman–Grahamtwo-processor precedence scheduling / layered drawingDAGs and Topological Sort
Colon and fusion principlesreduce green Hackenbush on any graph to a numberHackenbush
Color coding (Alon–Yuster–Zwick)k-vertex paths in O((2e)^k m) expectedRandomized Search
Commentz-Waltermulti-pattern Boyer–Moore over a reversed trieTheoretical Algorithms Catalog
Convex hull trick, Li Chao treemin / max of lines queries, DP speedupsConvex Hull Trick
Conway’s surreal numbersvalues of partizan gamesHackenbush and Partizan Games
Cook–Levin theoremSAT is NP-completeComplexity Theory and NP-Hardness
Cooley–Tukey FFTconvolution in FFT
Cooper–Harvey–Kennedysimple iterative dominator algorithmDominator Tree
Coppersmith–Winograd matrix multiplicationTheoretical Algorithms Catalog
Cops and robber (dismantlable graphs)one cop wins iff corners can be deleted down to one vertexGames on Graphs
Count-Min sketchapproximate frequency counts in small memoryFast Set and Integer Structures
Count–Min sketchfrequency estimates with additive error ΔnSampling and Streaming
Courcelle’s theoremMSO properties are linear-time on bounded treewidthComplexity Theory and NP-Hardness
Cover’s switching strategyrandomized threshold that beats in the two-envelope gameTwo Envelopes
Cramer’s ruleDeterminants and Permanents
Crochemore–Perrin (Two-Way) time, space string matching (glibc memmem)Theoretical Algorithms Catalog
Cycle lemmaexactly k good rotations of a sequence with steps at most 1 and sum kCatalan and Lattice Paths

D

NameWhat it doesNote
Damerau–Levenshteinedit distance with adjacent transpositionsLIS, LCS and Edit Distance
Dancing links (Algorithm X)exact cover searchExact Cover
de Bruijn graph / sequencecyclic sequence containing every length- word onceEuler Tours
de Fraysseix–Rosenstiehlleft-right planarity testSpecial Graph Classes
Delaunay / Voronoitriangulation and nearest-site diagramsDelaunay and Voronoi
Dial’s algorithmDijkstra with buckets for small integer weightsShortest Paths
Dijkstrasingle-source shortest paths, non-negative weightsShortest Paths
Dilworth, Mirskychain covers vs antichainsBipartite Matching
Dinicmax flow by blocking flowsMax Flow
Dinkelbach’s iterationfractional programming by repeated parametric solvesBinary Search
Dinur–Steurer hardness of set coverApproximation Algorithms
Divide and conquer DP optimizationmonotone optimum, D&C Optimization
Dobkin–Kirkpatrickhierarchical convex polyhedron for queriesPoint Location and Point Counting
Dominator tree (Lengauer–Tarjan)immediate dominators in flow graphsDominator Tree
Downey–Fellowsparameterized complexity, W-hierarchyComplexity Theory and NP-Hardness
Dreyfus–WagnerSteiner tree DP in Steiner Tree
DSU on tree (sack)offline subtree queries in Small to Large
Du’s sieve, Min_25 sieveprefix sums of multiplicative functions in sublinear timeSublinear Sieves
Dubins–Spanier moving knifeproportional cake cutting with cutsCake Cutting
Durand–Kernersimultaneous iteration for all polynomial rootsRoot Finding and Integration
DuvalLyndon factorization in Lyndon Words
Duval’s algorithmLyndon factorisation in O(n)Lyndon Words

E

NameWhat it doesNote
Edmonds’ arborescence (Chu–Liu)minimum directed spanning treeDirected MST
ErdƑs–Gallai theoremwhich degree sequences are graphical, via a partial-sum conditionSpecial Graph Classes
Edmonds–Karpmax flow by BFS augmenting pathsMax Flow
Eertreepalindromic tree: one node per distinct palindromeEertree
Eertree (palindromic tree)all distinct palindromes onlineEertree
Eisenstein’s criteriona sufficient condition for irreducibility over Polynomial Factorization
Eppstein’s algorithm shortest walks in K Shortest and Disjoint Paths
Eratosthenesprimes up to in Sieves
ErdƑs–Szekeres theorem distinct numbers contain an increasing run of or a decreasing one of Pigeonhole Puzzles
Eswaran–Tarjanminimum edges to make a digraph strongly connected: SCC and 2-SAT
Euclid’s formula (Pythagorean triples)all primitive triples as (mÂČ âˆ’ kÂČ, 2mk, mÂČ + kÂČ)Number Theory Miscellany
Euclid–Euler theoremeven perfect numbers are Primality Testing and Factorization
Euler transformcounting multisets / sets from object counts via expCounting with Power Series
Euler’s formula (planar graphs) for a graph embedded in the planePlanar Faces
Euler’s theorem, Fermat’s little theoremModular Arithmetic
Euler tour treelink / cut with subtree aggregatesEuler Tour Tree
Even–Pazproportional cake cutting with queries by divide and conquerCake Cutting
Extended EuclidBézout coefficients, inversesGCD and Extended Euclid

F

NameWhat it doesNote
Faddeev–LeVerrier algorithmcharacteristic polynomial and inverse from tracesCharacteristic Polynomial
Fagin’s theoremNP = existential second-order logicComplexity Theory
Farach-Colton–Bender / RMQRMQ
Farey sequence next termO(1) step to the next reduced fraction with denominator ≀ nBig Integers and Fractions
Farey sequencereduced fractions with bounded denominator, mediant neighboursContinued Fractions and Pell Equations
Feller’s weak law (St. Petersburg) St. Petersburg games pay about St. Petersburg Paradox
Fenwick tree (BIT)prefix sums with point updatesFenwick Tree
Fine–Wilf periodicity lemmaperiods p, q with give period String Basics
First Fit Decreasingbin packing within 11/9 OPT + 6/9Approximation Algorithms
Fisher–Yates shuffleuniform random permutation in Randomized Algorithms
FKM algorithmde Bruijn sequences from Lyndon wordsLyndon Words
Floyd’s cycle findingtortoise and hareFunctional Graphs
Floyd’s sampling algorithmk distinct uniform values from [0, n) in O(k)Sampling and Streaming
Floyd–Warshallall-pairs shortest paths Shortest Paths
FM-indexbackward search pattern counting on the BWTBurrows–Wheeler
Ford–Fulkersonaugmenting paths, max-flow min-cutMax Flow
Ford–Johnson (merge insertion)sorting with near-minimum comparisonsSorting, Selection and Inversions
Fortune’s algorithmVoronoi diagram by a sweep line in Delaunay and Voronoi
Frame–StewartTower of Hanoi with 4+ pegsTower of Hanoi
Fredman–TarjanFibonacci heaps; Dijkstra in Heaps
Fredman–Willardfusion trees: predecessor in Fast Set and Integer Structures
Fredricksen–Kessler–Maioranade Bruijn sequence by concatenating Lyndon wordsLyndon Words and Minimal Rotation
Freivalds’ algorithmcheck in per random trialRandomized Algorithms
Frobenius number (Chicken McNugget)largest non-representable amount Linear Congruences and CRT
Fuss–Catalan numbersk-ary trees, generalised ballotCatalan and Lattice Paths
FĂŒrer’s algorithminteger multiplication in Theoretical Algorithms Catalog

G

NameWhat it doesNote
Gabow’s algorithmpath-based SCC with two stacksSCC and 2-SAT
Gabow–Edmondsefficient weighted general matchingTheoretical Algorithms Catalog
Gabow–Tarjancost-scaling assignment and matchingAssignment Problem
Gale’s Hex theorema full Hex board has exactly one winner (boundary-walk proof)Chomp and Hex
Gale–Ryserwhich degree pairs are realisable by a bipartite graphSpecial Graph Classes
Gale–Shapleystable marriageStable Matching
Galil–Seiferaslinear-time string matching with extra spaceTheoretical Algorithms Catalog
Gallai–Edmonds decompositionstructure of maximum matchings in general graphsGeneral Matching
Garner’s algorithmmixed-radix CRT reconstruction (three-prime NTT)NTT
Garsia–Wachsoptimal alphabetic binary tree in Knuth-Yao Optimization
Gaussian elimination, Bareisslinear systems, rank, determinantGaussian Elimination
Gauss–Jordan eliminationreduced row echelon form, inverse, rankGaussian Elimination, Rank and Inverse
Gauss–Legendre quadratureexact for polynomials of degree Root Finding and Integration
Goemans–Williamson0.878-approximation of max-cut via an SDPApproximation Algorithms
Goldberg–Tarjanpush–relabel max flow; cost scalingMaximum Flow
Golomb–Dickman constantexpected longest cycle of a random permutation 100 Prisoners
Gomory’s domino theorema chessboard minus one white and one black square is domino-tileableMutilated Chessboard
Gomory–Hu treeall-pairs min cuts with flowsGomory-Hu Tree
Gonzalez farthest-point clustering2-approximation for k-centerApproximation Algorithms
Good–Thomas (prime-factor FFT)DFT of length , coprime factors, no twiddlesTheoretical Algorithms Catalog
Graeffe iterationroot squaring for polynomials and for Bostan–MoriComposition and Taylor Shift
Graham scanconvex hullConvex Hull
Gray codeadjacent subsets differ in one bitGray Code
Green’s theoremarea of a region from a boundary integral (circle union)Circle Union and Angular Sweep
Greene’s theoremRSK shape = sizes of disjoint increasing subsequencesYoung Tableaux and RSK
Grover’s algorithmquantum search in Complexity Theory and NP-Hardness
Guibas–Stolfidivide-and-conquer Delaunay with the quad-edge structureDelaunay and Voronoi
Guy–Smith periodicity theorema row game whose Grundy values repeat on a finite window is periodic foreverSprague–Grundy

H

NameWhat it doesNote
Hadamard boundDeterminants and Permanents
Half-GCDpolynomial gcd in O(n log^2 n)GCD and Resultant
Helly’s theoremif every of a family of convex sets in intersect, the whole family intersects; underlies LP-type algorithmsLinear Programming
Hall, König, Tuttematching existence and min-max theoremsBipartite Matching
Hall’s theorem / conditiona perfect matching of exists iff for every Bipartite Matching
Hamming distancenumber of differing positions (popcount of XOR)Bitset
Handshake lemma; the number of odd vertices is evenGraph Basics and Modeling
Han–Thorupinteger sorting in Theoretical Algorithms Catalog
Harel–Tarjanfirst / LCATheoretical Algorithms Catalog
Harmonic numbers, the harmonic-lemma boundHarmonic Lemma and Floor Sums
Hasse’s theoremTheoretical Algorithms Catalog
Havel–Hakimitest and construct a graph with a given degree sequenceSpecial Graph Classes
Heavy-light decompositionpath queries in HLD
Held–KarpTSP / Hamiltonian path DP in Hamiltonian Paths and TSP
Heron’s formulatriangle area from its side lengthsPolygons
Hessenberg methodcharacteristic polynomial in Characteristic Polynomial
Hessenberg reductioncharacteristic polynomial in O(n^3)Characteristic Polynomial
HierholzerEuler tours in Euler Tours
HirschbergLCS / alignment in linear spaceSequence DP
Hoeffding’s lemmatail bounds for bounded independent variablesProbability and Expectation
Hollow heapsimple heap with Fibonacci-heap boundsHeaps
Hopcroft–Karpbipartite matching Bipartite Matching
Hopcroft–Tarjanlinear DFS: biconnectivity, triconnectivity, planaritySpecial Graph Classes
Horner’s ruleevaluate a polynomial with multiplicationsRoot Finding and Integration
Horspool’s algorithmsimplified Boyer–Moore with one shift tableOther Matching
Hungarian (Kuhn–Munkres)assignment problem Assignment Problem
Hunt–SzymanskiLCS in with matching pairsLIS, LCS and Edit Distance
Hu–Shing matrix-chain multiplicationInterval DP
Hu–Tuckeroptimal alphabetic code treeKnuth-Yao Optimization
HyperLogLogdistinct count with relative error ≈ 1.04/√mSampling and Streaming

I

NameWhat it doesNote
Irving’s algorithmstable roommatesStable Matching
Itai–Papadimitriou–SzwarcfiterHamiltonian paths in grid graphsHamiltonian Paths and TSP

J

NameWhat it doesNote
Jensen’s inequalityfor convex , mean of (reverse for concave)🐬 Formula
Johnsonall-pairs shortest paths with reweightingShortest Paths
Jonker–Volgenantfast shortest-augmenting-path assignmentAssignment Problem
Josephus problem survivor recurrence and the jumpClassic Puzzles

K

NameWhat it doesNote
Kac’s lemmaexpected return time in a Markov chainProbability and Expectation
Kadanemaximum subarrayClassic Array Problems
Kahn’s algorithmBFS topological sort by in-degreeDAGs and Topological Sort
Kaltofen–Shoupsubquadratic distinct-degree factorizationPolynomial Factorization
Karatsuba multiplication3 half-size products, O(n^1.585)Fast Fourier Transform
Karatsubamultiplication in FFT
Karger, Karger–Steinrandomized global min cutGlobal Min Cut
Karger–Klein–Tarjanrandomized linear-time MSTTheoretical Algorithms Catalog
Kariv–Hakimiabsolute 1-center of a graphMinimum Spanning Trees
Karlin–Klein–Oveis Gharan-approximation for metric TSPApproximation Algorithms
Karmarkar–Karp (differencing)largest-differencing heuristic for number partitioningScheduling and Partitioning
Karp’s minimum mean cycleminimum mean-weight cycle in Shortest Path Techniques
Karp–Miller–Rosenberg namingprefix doubling: O(1) equality of substringsSuffix Array
Karp–Miller–Rosenbergprefix doubling for suffix arrays / namingSuffix Array and LCP
KasaiLCP array from a suffix array in Suffix Array
Kasai’s algorithmLCP array from the suffix array in O(n)Suffix Array
Kasteleyn’s formuladomino tilings via a PfaffianBroken Profile DP
Kawarabayashi–Thorupdeterministic near-linear min cut in simple graphsGlobal Minimum Cut
Kaylesremove 1 or 2 adjacent pins; Grundy period 12 from 71Sprague–Grundy
King–Rao–Tarjandeterministic max flow in for dense graphsTheoretical Algorithms Catalog
Kinoshita–Li compositionf(g(x)) mod x^n in O(n log^2 n) via power projectionComposition and Taylor Shift
Kirkman triple systemresolvable Steiner triple system; exists iff Kirkman’s Schoolgirls
Kirkpatrick–Seidel”ultimate” convex hull in Convex Hull
Kitamasa’s methodn-th term of a linear recurrence in O(k^2 log n)Linear Recurrences
Kleitman–Kwiatkowski bounda Fitch Cheney trick with cards exists iff the deck has at most cardsFitch Cheney Trick
KMP (prefix function)pattern matching, borders, periodsPrefix Function and Z
Knuth–Morris–Pratt algorithmlinear-time matching with the prefix functionPrefix Function and Z
Knuth–Morris–Prattlinear string matching with the prefix functionPrefix Function and Z-Function
Knuth–Plassoptimal line breaking (monotone DP)Monotone Queue, 1D1D and SMAWK
Knuth–Yao optimizationinterval DP in Knuth Optimization
Knuth–Yao speedup interval DP under the quadrangle inequalityKnuth-Yao Optimization
Kummer’s theoremp-adic valuation of a binomial = number of carriesBinomial Identities
König–EgervĂĄry, König–Orebipartite max matching = min vertex cover; deficiency formulaBipartite Matching
Kosaraju, Tarjan SCCstrongly connected componentsSCC and 2-SAT
KruskalMST with a DSUMST
Kruskal reconstruction treebottleneck paths, reachability under thresholdsKruskal Reconstruction Tree
Kuhnbipartite matching by augmenting DFSBipartite Matching
Kuratowski’s theoremplanar iff no or subdivisionSpecial Graph Classes

L

NameWhat it doesNote
Lagrange interpolationpolynomial from point valuesInterpolation
Lagrange inversioncoefficients of compositional inversesGenerating Functions
Lanczos algorithmKrylov tridiagonalisation for symmetric eigenproblemsSparse and Structured Matrices
Landau–Vishkin-differences matching in LIS, LCS and Edit Distance
Larmore–Schieberconcave 1D/1D DP in linear timeMonotone Queue, 1D1D and SMAWK
Lasker’s Nimremove or split a heap; Grundy values swap within blocks of 4Sprague–Grundy
Legendre’s formula, Kummer, Lucasprime powers in factorials and binomialsFactorials mod p
Lehmer codepermutation factorial number system, rank and unrankCounting Fundamentals
Lempel–Even–Cederbaumst-numbering-based planarity testSpecial Graph Classes
Lempel–ZivLZ77/LZ78 factorization and compressionRuns and Periodicity
Lenstra ECMelliptic-curve factorizationTheoretical Algorithms Catalog
Lenstra–Lenstra–Lovász (LLL)lattice basis reductionPolynomial Factorization
Lenstra–Shmoys–Tardos2-approximation for unrelated machine schedulingScheduling and Partitioning
Levenshtein distanceedit distance DPLIS, LCS and Edit Distance
Lichtenberg–Thorup (Holm–de Lichtenberg–Thorup)fully dynamic connectivity in amortizedDynamic Connectivity
Lindström–Gessel–Viennot lemmanon-intersecting lattice paths as a determinantDeterminants
Lindström–Gessel–Viennotnon-intersecting lattice paths as a determinantDeterminants and Permanents
Linear conflict heuristicManhattan distance plus 2 per tile that must leave its line; admissible for sliding puzzlesFifteen Puzzle
Link-cut treedynamic trees with path aggregatesLink-Cut Tree
Lin–Kernighanvariable-depth local search for TSPHamiltonian Paths and TSP
Lipton–Tarjanplanar separator theorem, separatorsSpecial Graph Classes
LPT schedulinglongest processing time first, (4/3 − 1/(3m))-approximate makespanApproximation Algorithms
Lucas–Lehmerprimality test for Mersenne numbersPrimality Testing and Factorization
Lucy_Hedgehog’s algorithm and prime sums in Sublinear Sieves and Prime Counting
LUX method (Conway)magic squares of order Magic Squares

M

NameWhat it doesNote
MacNeish constructionKronecker products of orthogonal Latin squaresLatin Squares
Main–Lorentz algorithmall runs / tandem repeats in O(n log n)Runs and Periodicity
Main–Lorentzall tandem repeats in Runs and Periodicity
Malhotra–Kumar–Maheshwari (MPM) blocking-flow max flowMaximum Flow
Mantel’s theorema triangle-free graph on vertices has at most edges (the case of Turán)Constructive Algorithms
Manacherall palindromic radii in Palindromes
Manacher’s algorithmall maximal palindromes in O(n)Palindromes
Manber–Myers suffix array by doublingSuffix Array and LCP
Manhattan distance; MST and farthest pair via Attacking a Problem
Matrix-tree theorem (Kirchhoff)counting spanning treesMatrix-Tree Theorem
McCreightlinear-time suffix treeTheoretical Algorithms Catalog
Megiddo’s algorithm2D/3D linear programming in (prune and search)Linear Programming
Meissel–Lehmer in about Sublinear Sieves and Prime Counting
Moore’s Nimremove from up to k heaps; losing iff every bit column sums to 0 mod k+1Combinatorial Games and Nim
Myers’ bit-vector algorithmedit distance in O(n m / w)Other Matching
Ménage problemseating couples alternately with no partners adjacentInclusion-Exclusion and Derangements
Menger’s theoremmax disjoint paths = min cutMinimum Cut
Mersenne numbers, Lucas–Lehmer testPrimality Testing and Factorization
Mertens’ theoremsPrimes and Sieves
Metropolis criterionacceptance rule in simulated annealingHeuristic Optimization
Micali–Vaziranigeneral matching in General Matching
Miller–Rabindeterministic 64-bit primalityPrimality and Factorization
Miller–Reifparallel tree contraction (rake and compress)Top Trees
Minkowski sumsum of convex polygons in Minkowski Sum
Misra–Griesheavy hitters, more than occurrences, in spaceClassic Array Problems
Mo’s algorithm (and variants)offline range queries in Mo’s Algorithm
Möbius inversioninclusion–exclusion over divisorsArithmetic Functions
Monge condition, which gives monotone argminsMonotone Queue, 1D1D and SMAWK
Montgomery multiplicationdivision-free modular productsBarrett and Montgomery
Moon–Mosera graph has at most maximal cliquesMaximum Clique and Independent Set
Moore–Hodgsonminimise the number of late jobsScheduling and Partitioning
Moore–Penrose pseudoinverseleast-squares solutionsRoot Finding and Integration
Mucha–Sankowskimatching via Gaussian elimination in General Matching
Mycielski constructiontriangle-free graphs of any chromatic numberConstructive Algorithms

N

NameWhat it doesNote
Nagamochi–Ibarakisparse -connectivity certificatesGlobal Min Cut
Nash-Williams–Tutte edge-disjoint spanning trees; arboricity formulaMatroids
Needleman–Wunschglobal sequence alignmentLIS, LCS and Edit Distance
Nemhauser–Trotterhalf-integral vertex cover LP, kernelComplexity Theory and NP-Hardness
Nemhauser–Wolsey–Fishergreedy gives for monotone submodular maximisationApproximation Algorithms
Network simplexfast practical min-cost flowMin-Cost Flow
Newton iteration (power series)inverse, log, exp, sqrt of a series in Power Series Operations
Newton’s identitiespower sums elementary symmetric polynomialsCharacteristic Polynomial
Newton’s method (power series)inverse, log, exp, sqrt of seriesPower Series
Newton–Raphsonquadratically convergent root findingRoot Finding and Integration
Newton–Schulz iterationmatrix inverse with only multiplications, quadratic convergenceRoot Finding and Integration
Newton–Schulziterative matrix inverseRoot Finding and Integration
Non-adjacent form (NAF)signed binary digits with no two adjacent non-zeros, minimal weightNumber Theory Miscellany
NTTexact convolution modulo primesNTT
Number-theoretic transformexact FFT over Z_p with p = c 2^k + 1NTT

O

NameWhat it doesNote
Ore’s theorem for non-adjacent implies HamiltonianHamiltonian Paths and TSP
Orlin’s algorithmstrongly polynomial min-cost flow; max flowTheoretical Algorithms Catalog
Otter’s dissimilarity theoremunlabelled free trees from rooted treesCounting Graphs and Trees
Otter’s formulacounting unlabelled treesTree Isomorphism and PrĂŒfer Codes

P

NameWhat it doesNote
Pairing heapsimple meldable heap, fast in practiceHeaps
Papadimitriou’s random walk2-SAT in O(nÂČ) expected flipsRandomized Search
Parallel binary searchmany monotone searches at onceParallel Binary Search
Pascal’s rule, Pascal’s triangleCounting Fundamentals
Pentagonal number theorempartition numbers in O(n sqrt n); Franklin’s involutionStirling, Bell and Partitions
Pisano periodperiod of Fibonacci numbers modulo mNumber Theory Miscellany
Power tower (generalized Euler theorem)a^x ≡ a^(x mod φ(m) + φ(m)) mod m for x ≄ φ(m)Number Theory Miscellany
Principal variation search (NegaScout)null-window alpha-beta with re-searchGame Search
Proof-number searchbest-first proof of a forced win with proof / disproof numbersGame Search
PĂ©pin’s testprimality of Fermat numbersTheoretical Algorithms Catalog
Persistent segment treeversioned arrays, -th smallest in a rangePersistent Segment Trees
Pettie–Ramachandranoptimal (decision-tree-optimal) MST algorithmTheoretical Algorithms Catalog
Picard–Queyranneall minimum - cuts from a residual graphMinimum Cut
Pick’s theorem for lattice polygonsPolygons
Pigeonhole principle objects in boxes; prefix sums mod Invariants, Parity and Extremal Arguments
Pohlig–Hellmandiscrete log in a group of smooth orderPrimitive Roots and Discrete Log
Pollard’s factor when is smoothPrimitive Roots and Discrete Log
Pollard’s rho (Brent)64-bit factorization in Primality and Factorization
PrimMST in or MST
Push–relabel (HLPP)max flow for dense / hard graphsPush-Relabel

Q

NameWhat it doesNote
q-Lucas theoremq-binomials modulo p when q has small orderStirling, Bell and Partitions
Quadratic sievesubexponential factorizationTheoretical Algorithms Catalog

R

NameWhat it doesNote
Radon’s theoremany points in split into two sets whose convex hulls intersectLinear Programming
Rabin’s irreducibility testirreducibility over F_p via x^(p^n) - xPolynomial Factorization
Rabin–Karp algorithmpattern matching with rolling hashesString Hashing
Rabin–Karprolling-hash matchingString Hashing
Rabin–Vaziranirandomized matching via the Tutte matrixGeneral Matching
Rader’s algorithmprime-length DFT via cyclic convolutionConvolution Variants
Rado–Edmondsgreedy is optimal exactly on matroidsMatroids
Raghavan–Thompsonrandomized rounding with Chernoff boundsApproximation Algorithms
Ramsey’s theorem: any 2-colouring of ‘s edges has a monochromatic triangle, and generally is finiteParty Problem
Randomized rounding (Raghavan–Thompson)round an LP solution by treating values as probabilitiesApproximation Algorithms
Rearrangement inequalitysimilarly ordered sequences maximise Greedy and Exchange Arguments
Reeds–Sloane algorithmshortest linear recurrence modulo a compositeLinear Recurrences
Reed–Solomonpolynomial evaluation codesPolynomial Factorization
Reeds–SloaneBerlekamp–Massey modulo composite Linear Recurrences
Reifplanar min cut / max flow via shortest paths in the dualTheoretical Algorithms Catalog
Relaxed multiplicationonline convolution in O(n log^2 n)Online Convolution
Reservoir sampling (Algorithm R, Algorithm L)uniform k-sample of a stream in O(k) memorySampling and Streaming
Retrograde analysiswin / loss / draw of a cyclic game graph backwards from terminal positionsLoopy Games
Robbins’ theoremstrongly orientable iff 2-edge-connectedBridges and Biconnectivity
Robinson’s recurrencecounting labelled DAGs by inclusion–exclusion over sourcesCounting Graphs and Trees
Rotating calipersdiameter, widths, antipodal pairsRotating Calipers
RSK correspondence, hook length formulaYoung tableaux countingYoung Tableaux and RSK
Rule of three (peg solitaire)diagonal 3-colouring parity invariant of peg solitairePeg Solitaire
Runs theorema string has fewer than maximal repetitionsRuns and Periodicity
Ryser’s formulapermanent in Determinants and Permanents

S

NameWhat it doesNote
SA-ISsuffix array in Suffix Array
Schieber–Vishkin LCA after preprocessingLCA
Schreier–Sims algorithmorder and membership of a permutation groupBurnside and Pólya
Schwartz–Zippel lemmaa non-zero degree-d polynomial vanishes at a random point with probability Hashing and Verification
Schönhage–Strasseninteger multiplication in Theoretical Algorithms Catalog
Schreier–Simspermutation group order and membershipBurnside and Pólya
Schroeppel–Shamirmeet in the middle with memoryMeet in the Middle
Schwartz–Zippela random point detects a nonzero polynomial with probability Randomized Algorithms
Schwenk’s theoremwhich boards admit a closed knight’s tourBacktracking and Pruning
Schöning’s algorithmrandom-walk 3-SAT in O((4/3)^n poly n)Randomized Search
Secretary problemoptimal stopping, skip , success Secretary Problem
Segment tree beats (Ji driver)range chmin / chmax with sumsSegment Tree Beats
Seidel’s algorithmrandomized LP in fixed dimension, expected Linear Programming
Seidel’s LPrandomized incremental LP in fixed dimension, expected O(d! n)Linear Programming
Selfridge–Conwayenvy-free cake cutting for 3 people with at most 5 cutsCake Cutting
Shamos–Hoeydetect any segment intersection in Sweep Line and Segment Intersections
Sharir–WelzlLP-type problems, randomizedLinear Programming
Sherman–Morrison formulainverse after a rank-one update in O(n^2)Sparse and Structured Matrices
Sherman–Morrisonrank-1 update of a matrix inverseSparse and Structured Matrices
Shoelace formulapolygon area from its vertex coordinatesPoints, Vectors and Orientation
Siamese methododd-order magic squaresConstructive Algorithms
Simpson’s ruleadaptive numerical integrationRoot Finding and Integration
Simulated annealingMetropolis acceptance with a cooling scheduleHeuristic Optimization
Skew heap, leftist heapmeldable heaps in Heaps
Skolem constructionSteiner triple system on points from a half-idempotent quasigroupKirkman’s Schoolgirls
Sleator–Tarjanlink-cut trees; splay treesLink-Cut Tree
Slope trickDP over convex piecewise-linear functionsSlope Trick
SMAWKrow minima of totally monotone matrices in Monotone Optimizations
Smith’s ruleminimise weighted completion time: sort by Scheduling and Partitioning
Smith–Watermanlocal sequence alignmentLIS, LCS and Edit Distance
SOS DP (zeta / Möbius transform)sums over subsets in Submasks and SOS DP
Sparse table idempotent range queriesSparse Table
Sperner’s theoremthe largest antichain in has size Modular Arithmetic
SPFABellman–Ford with a queueShortest Paths
Splay treeself-adjusting BST, amortized Treaps and Balanced BSTs
Sprague–Grundyimpartial game sumsSprague-Grundy
Staircase NimNim on the odd-indexed stepsCombinatorial Games and Nim
Stanley sequencegreedy 3-AP-free sequence (base-3 digits)Constructive Algorithms
Stern–Brocot simplest fractionsmallest-denominator fraction in an interval in O(log) via continued fractionsBig Integers and Fractions
Stern–Brocot treerationals, best approximationsContinued Fractions
Stirling numberscycles (first kind) and set partitions (second kind)Stirling, Bell and Partition Numbers
Stirling’s approximation🐬 Formula
Stoer–Wagnerdeterministic global min cutGlobal Min Cut
Strassen’s algorithmmatrix product with 7 block multiplications, O(n^2.807)Matrices and Matrix Power
Strategy stealingthe first player wins (Chomp, Hex) without an explicit strategyChomp and Hex
Subproduct treemultipoint evaluation and interpolation in O(n log^2 n)Evaluation and Interpolation
Suffix automatonall substrings in statesSuffix Automaton
Surreal numbersConway’s numbers as game valuesHackenbush and Partizan Games
Sutherland–Hodgmanclip a polygon against a convex polygonPolygons
Suurballe’s algorithm edge-disjoint shortest paths of minimum total lengthK Shortest and Disjoint Paths
Sweep line (Bentley–Ottmann)segment intersectionsSweep Line
Swinnerton-Dyer polynomialsworst case for Zassenhaus factorizationPolynomial Factorization
Sylvester’s identitydeterminant identity behind Bareiss eliminationDeterminants and Permanents
Sylvester–Gallainon-collinear points have an ordinary lineInvariants, Parity and Extremal Arguments

T

NameWhat it doesNote
Tabu searchlocal search with a memory of forbidden movesHeuristic Optimization
Tango tree-competitive BSTFast Set and Integer Structures
Tarjan bridges / articulation pointslowlinkBridges and Biconnectivity
Tarjan offline LCALCA with a DSULCA
Tarjan–Vishkinbiconnected components via spanning-tree connectivityBridges and Biconnectivity
Tarjan–Werneckself-adjusting top treesTop Trees
Tarjan–Yannakakismaximum cardinality search, chordality testSpecial Graph Classes
Thomas algorithmtridiagonal systems in O(n)Sparse and Structured Matrices
Thue–Morse anti-hashstrings of length 2^11 collide under every polynomial hash mod 2^64Hashing and Verification
Thue–Morse sequenceparity of popcount; breaks hashes mod String Hashing
Toom–Cook split-into-3 multiplicationFast Fourier Transform
Top treedynamic trees with path and subtree dataTop Trees
Touchard’s formulamĂ©nage problem count via rook numbers on a cycleInclusion–Exclusion
Toussaint’s rotating caliperswidth, diameter and bounding boxes of convex polygonsRotating Calipers
Treaprandomized balanced BST, implicit keysTreaps
Trygub numbersbig numbers with digits allowed to go negative, updatesModular Arithmetic
Tsin’s algorithm3-edge-connected componentsBridges and Biconnectivity
Turán’s theorem, Turán graphmax edges without a Constructive Algorithms
Tutte–Berge formulamax matching General Matching
Two-SATimplication graph + SCCSCC and 2-SAT

U

NameWhat it doesNote
Ukkonensuffix tree onlineSuffix Tree
Ukkonen’s algorithmonline suffix tree constructionSuffix Tree

V

NameWhat it doesNote
van Emde Boas treepredecessor in Fast Set and Integer Structures
Vandermonde’s identityBinomial Identities
Vertex geography (Gallai–Edmonds)first player wins iff every maximum matching covers the startGames on Graphs
Vizing’s theoremchromatic index is or ; constructive edge-colouring by fan rotationsGraph Coloring

W

NameWhat it doesNote
Walsh–Hadamard transformxor / and / or convolutionsBitwise Convolutions
Warnsdorff’s ruleknight’s tour heuristic: fewest onward moves firstBacktracking and Pruning
Wedderburn–Etherington numbersunlabelled binary rooted treesTree Isomorphism and PrĂŒfer Codes
Weiler–Athertonclip general (non-convex) polygonsPolygons
Weiner’s algorithmfirst linear-time suffix treeTheoretical Algorithms Catalog
Weiszfeld’s iterationgeometric medianMinimum Enclosing Circle
Welzlminimum enclosing circle in expected Minimum Enclosing Circle
Wiedemann’s algorithmsparse solve / determinant via Krylov sequence + Berlekamp–MasseySparse and Structured Matrices
Wilson’s algorithmuniform spanning tree by loop-erased random walksMatrix-Tree Theorem
Wilson’s sliding-puzzle theoremon a 2-connected bipartite graph (not a cycle or ) sliding tokens realise exactly the even permutationsFifteen Puzzle
Wilson’s theoremFactorials and Binomials mod p
Winding numberpoint in polygon for self-intersecting polygonsPolygons
Worpitzky’s identitypowers as sums of Eulerian numbers times binomialsStirling, Bell and Partitions
Wu–Manberhashed multi-pattern shift matchingTheoretical Algorithms Catalog
Wythoff’s gamelosing positions Sprague-Grundy

Y

NameWhat it doesNote
Yao’s minimax principlelower bounds for randomized algorithmsComplexity Theory and NP-Hardness
Yen’s algorithm shortest simple pathsK Shortest and Disjoint Paths
Yun’s algorithmsquare-free decompositionPolynomial Factorization

Z

NameWhat it doesNote
Z-algorithmlongest common prefix with every suffix in O(n)Prefix Function and Z
Z-functionlongest common prefix with every suffixPrefix Function and Z
Zassenhausfactor integer polynomials via Hensel liftingPolynomial Factorization
Zeckendorf representationunique sum of non-consecutive Fibonacci numbers, found greedilyNumber Theory Miscellany
Zermelo’s theoremevery finite two-player perfect-information game is determined: one player has a forced win, or both can force at least a draw; backward induction (minimax) finds whichGame Search
Zeller / misc date and number trickssee the formula list🐬 Formula
Zobrist hashingXOR of random keys per state componentRandomized Algorithms
Zsigmondy’s theoremfor coprime , has a prime factor dividing no earlier , except a few small cases—