The Great Paradigms
Which few ideas produce most good algorithms, and how far can a better decomposition go?
The part opens with a million digits of pi, certified between two bounds, and two million-digit numbers multiplied several ways. Greedy comes first: interval scheduling by earliest finish, proved by an exchange argument, then coins and matchings where a plausible rule fails, and Whitney's matroids, the structures on which greedy is right for every nonnegative weighting. Divide and conquer follows: Karatsuba's three half-size products instead of four, Strassen's seven instead of eight, and the fast Fourier transform, which evaluates a polynomial at the roots of unity because squaring them halves their number at every level. The FFT multiplies integers, and the part is careful about what that needs: a small rounding distance is a diagnostic, and the certificate is an exact check modulo two primes. Dynamic programming fills tables for edit distance, knapsack, matrix chains and trees, and backtracking with Dancing Links searches where no structure is known. The part ends with the maximum subarray solved four ways, cubic to linear, and with the open questions about the exponent of matrix multiplication, edit distance under SETH and circuits for the DFT.
What you need. Complex numbers on the unit circle, and matrix multiplication.
- Mathematics, ideas and history
- greedy and matroids, Karatsuba and Strassen, the FFT, dynamic programming, Held–Karp, Dancing Links
- What we build or compute
- FFT big-number multiplication; DP tables
What you will be able to do
Degree
- Prove a greedy rule correct by an exchange argument, and give a counterexample to a rule that only looks plausible.
- Fill and trace back the tables for edit distance and knapsack, and explain why O(nW) is pseudo-polynomial.
- Solve the maximum-subarray problem by Kadane's recurrence and say what each of the four methods reuses.
Graduate
- Derive Karatsuba's and Strassen's recurrences and solve them, counting the additions as well as the products.
- Derive the FFT from the even and odd split at the roots of unity, and prove the inverse by orthogonality.
- Prove that greedy is optimal for every nonnegative weighting of a hereditary system exactly when the system is a matroid.
Research
- State what a barrier for the laser method restricts and what it leaves open about the matrix multiplication exponent.
- Explain how a truly subquadratic exact edit-distance algorithm would contradict SETH, and why Morgenstern's bound does not cover circuits with unrestricted coefficients.
Industry
- Certify a floating-point FFT product with an independent exact check instead of trusting the distance to the nearest integer.
- Choose a multiplication method and a cutoff from measurements, stating the timing boundary: what was converted, carried and checked outside the timer.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 24 min · Graduate 41 min · Research 44 min · Industry 27 min.
- 0A million digitsDegree2 min
- 1Greedy, and the exchange argumentDegree3 min
- 2When greedy is right: matroidsGraduate2 min
- 3Three products instead of fourDegree3 min
- 4Seven products instead of eightGraduate3 min
- 5The FFT, I: values instead of coefficientsDegree3 min
- 6The FFT, II: butterfliesGraduate3 min
- 7What the FFT multipliesIndustry3 min
- 8The closest pairGraduate2 min
- 9Dynamic programmingDegree2 min
- 10Edit distanceDegree2 min
- 11Knapsack, and pseudo-polynomial timeDegree2 min
- 12Matrix chains and optimal search treesGraduate2 min
- 13Dynamic programming on trees, graphs and sequencesGraduate2 min
- 14Backtracking and Dancing LinksDegree3 min
- 15One problem, four paradigmsDegree2 min
- 16Frontier: how fast can we multiply?Research3 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
A million digitsDegree2 min
Here are leading digits of pi, and the final ten after one million decimal places. The Chudnovsky brothers' series adds roughly fourteen digits per term. Our binary splitting sums rational terms with exact integers. A finite sum and an integer square root still need error bounds. We bracket the infinite series between adjacent alternating partial sums, bracket the square root, and keep guard digits until both bounds give the same truncated integer. The displayed time covers that certified calculation; decimal conversion is separate.
Compare the work carefully. Grade-school digit convolution has quadratic growth; this million-digit time is an unexecuted projection from smaller tests. Python's integer row is a complete multiplication of two fixed million-digit operands, already converted to integers. The decimal row uses the same values with preconverted decimal operands; every product is checked exactly outside the timer. The separate FFT-core row times convolution and rounding on different digit arrays. It excludes conversion and carry, so it is not an end-to-end speed comparison. Algorithm, representation and timing boundary all matter. Chapters three and seven separate them.
Several ideas organize this part. Greedy chooses the best-looking next step; an exchange proof tells us when that choice is safe. Divide and conquer splits a problem, solves smaller pieces and combines their answers. The right decomposition gives Karatsuba, Strassen and the FFT. Dynamic programming reuses subproblem answers in a valid dependency order. Search explores choices and restores state when it backtracks. We will compare their mathematics, actual work and measured implementations.
1Greedy, and the exchange argumentDegree3 min
Each meeting has a start and an end; every meeting counts equally, and touching endpoints are allowed. Choose the largest nonoverlapping subset. Sort by finishing time and accept the next meeting whose start is at least the last accepted finish. Checking that one boundary is enough because the accepted meetings are ordered. This instance admits four meetings, matching the independently computed optimum. Sorting costs n log n comparisons; the finish-rule scan is linear. Other plausible rules will fail.
The proof is called an exchange argument. Greedy's first meeting finishes no later than any meeting at all. Take any best schedule and swap its first meeting for greedy's. Greedy's ends earlier, so it cannot clash with anything that came after; the schedule is still valid and just as large. So some best schedule begins with greedy's choice, and the rest of it is a best schedule for the meetings that start later, where the same argument applies. By induction, greedy is never behind. That is the shape of nearly every greedy proof: show that a best solution can be changed, one step at a time, into the greedy one without getting worse.
A plausible rule still needs a proof. These four rules run on two thousand fixed random instances. Earliest finish matches the optimum throughout; that experiment illustrates the theorem. Fewest conflicts still fails on the displayed fifteen-meeting witness. Shortest first chooses the middle interval and loses two compatible intervals. Starting first can lose many. With coin values one, three and four, greedy pays six using three coins, while dynamic programming finds two. The displayed failure count covers amounts one through ninety-nine. The one-five-ten-twenty-five system passes that finite range; the experiment alone does not prove canonicality for all amounts.
Huffman coding minimizes the weighted length of a binary prefix code for known symbol frequencies. Repeatedly merge the two lightest symbols or subtrees. Some optimal binary code tree puts two least-frequent symbols as deepest siblings; contracting that pair gives a smaller instance and the exchange proof. These frequencies come from letters and single spaces between words in thirty novels. We check the complete code's Kraft sum and weighted length against an independent merge-cost calculation. Entropy is a real-valued lower bound, not necessarily an attainable average for a one-symbol binary prefix code. Block coding can approach it under the corresponding source assumptions.
2When greedy is right: matroidsGraduate2 min
In 1935 Hassler Whitney noticed that independence behaves the same way in very different places. Take a ground set and call some of its subsets independent, with three rules. The empty set is independent. Any subset of an independent set is independent. And the exchange rule: if one independent set is smaller than another, it can always borrow some element of the larger one and stay independent. Linearly independent vectors obey these rules; that is where the name matroid comes from. So do the edge sets without cycles in a graph. Here the two blue edges form a forest, the three green edges a larger one, and the blue set can take a green edge without closing a cycle. And trivially, all sets of at most k elements.
The greedy theorem needs its weight convention. For nonnegative weights, consider elements from heaviest to lightest and keep each if independence is preserved. For arbitrary signed weights, discard negative elements when the goal is any independent set. Among finite hereditary independence systems, greedy is optimal for every nonnegative weighting exactly when the system is a matroid. Compare greedy's and an optimum's elements in descending order. Exchange says that an allegedly heavier next optimum element would have had an eligible predecessor at least that heavy. Greedy would already have taken it, a contradiction. On forests, descending order gives a maximum-weight forest. Kruskal's minimum spanning tree uses ascending order. Our four hundred nonnegative test graphs are checked by exhaustive enumeration.
Matchings show why the exchange axiom matters. Greedy takes the middle edge of weight three and blocks both neighbors. The two outer edges total four. The smaller matching containing the middle edge cannot borrow either edge from the larger matching. The random-instance success rate and worst ratio shown here describe these four hundred nonnegative graphs, not a universal distribution. For nonnegative edge weights, greedy always gets at least half the optimum: charge each rejected optimum edge to a greedy edge at least as heavy; at most two charges meet one chosen edge. Exact cardinality and weighted matching need further algorithms.
3Three products instead of fourDegree3 min
Karatsuba recalled a Moscow seminar in 1960, led by Andrey Kolmogorov. The challenge was whether multiplying n-digit integers really required quadratic work. The familiar school algorithm did; that did not establish a lower bound for every algorithm. Anatoly Karatsuba found a decomposition using three half-size products rather than four. The result appeared in a 1962 paper by Karatsuba and Yuri Ofman. Its lasting lesson is mathematical: a better algebraic identity can change the exponent, not merely tune a constant.
Here is the trick. Split each number into a high half and a low half. The product needs four half-size products: high times high, low times low, and the two cross terms. But the two cross terms are only needed as a sum, and that sum is the product of the two half-sums, minus the two products we already have. Three multiplications instead of four, paid for with a few additions, which are cheap. For 1234 times 5678: twelve times fifty-six, thirty-four times seventy-eight, and forty-six times one hundred and thirty-four, from which the middle term follows by subtraction. Three products give seven million and six thousand, six hundred and fifty-two.
The three-product decomposition recurses. One multiplication becomes three half-size problems, then nine quarter-size problems and twenty-seven eighth-size problems. For a power-of-two coefficient-array length, recursing to scalar leaves gives three to the log-base-two n leaves. Additions cost linear work at each node, yielding the n-to-log-base-two-three recurrence. Integer implementations also handle carries and the extra width of sums. The rectangular school model has n squared products. Our measured school loop skips zero left digits, so the table distinguishes that model from its actual multiplication count.
These runs use preconverted decimal digit arrays and return coefficient convolutions. We carry and compare every timed result with Python's exact integer product after stopping the timer. The counters record actual scalar products, including the school's skipped zero rows. A cutoff of thirty-two reduces recursive overhead; the table shows the observed crossover on this host rather than a hardware-independent threshold. CPython similarly combines school multiplication and Karatsuba, but its machine-digit threshold is an implementation choice, not thirty-two decimal digits. Toom-Cook uses evaluation and interpolation to reduce products further. The FFT takes that principle to many carefully chosen evaluation points.
4Seven products instead of eightGraduate3 min
Nine years later Volker Strassen did the same to matrices, in a paper titled Gaussian elimination is not optimal. Split each matrix into four blocks. The product needs eight block products, two for each block of the answer. Strassen found seven products of sums and differences of blocks, coloured here, from which all four answer blocks follow by addition alone. They work because blocks need not commute: no step ever swaps the order of a product, so the identities hold for blocks, and the method recurses. Seven half-size products and some additions give n to the log of seven, about n to the two point eight one, against n cubed.
This table counts a specified recursion down to scalar leaves. Each ordinary block step uses eight products and four additions; Strassen uses seven products and eighteen additions or subtractions. The totals include every recursion node. The linear combination work is quadratic at one node, but summed over the tree it has the same n-to-log-base-two-seven exponent as the leaf products. The practical implementation stops at blocks of size two hundred and fifty-six.
Omega is an asymptotic arithmetic exponent, not a stopwatch reading. It is the infimum of exponents achievable for square matrix multiplication, allowing arbitrarily small positive slack. Strassen gives log-base-two seven. The historical steps here include Coppersmith and Winograd's 1990 construction. The dated selections include Alman and coauthors' 2024 bound, and Dupont and coauthors' August 2026 refinement below two point three seven one one seven seven. They are selected published claims, not an exhaustive latest-record survey or an implementation in this course. Writing an explicit dense answer already requires quadratic output size in the usual arithmetic model. An exponent gain can coexist with enormous constants. Our small Strassen benchmark cannot establish a crossover for those research constructions.
The benchmark compares complete matrix products on fixed float64 inputs. Strassen delegates blocks of size two hundred and fifty-six to NumPy. Every timed output is checked; raw trials and the actual BLAS backend and configured thread count are recorded. The table reports this host's observations, not a universal winner or a measured explanation of cache behavior. The separate accuracy example compares both results with an extended-precision accumulation of the already rounded inputs. That reference is approximate: these are disagreements, not certified true errors. Cutoff, conditioning, layout and backend affect the tradeoff. AlphaTensor's 2022 forty-seven-product example concerns four-by-four multiplication modulo two; that field qualification is essential.
5The FFT, I: values instead of coefficientsDegree3 min
The fast Fourier transform, part one: values instead of coefficients. Polynomial multiplication separates the algebra from carries. Two coefficient arrays of length n have a rectangular school product with n squared scalar multiplications. At each evaluation point, the product value is just the two factor values multiplied together. Distinct points determine a polynomial up to its degree bound. A product of two degree-below-n factors has degree at most two n minus two, so it needs at least two n minus one values. Pad to a suitable transform length, evaluate both factors, multiply pointwise and interpolate. Arbitrary evaluation can still cost quadratic work. The FFT's gain comes from choosing points that share recursive calculations.
Split the coefficients by parity. The even and odd parts are polynomials in x squared. Evaluate at opposite points, x and minus x. Both use the same two half-polynomial values; only the sign of the odd contribution changes. Each opposite pair therefore shares its recursive work. To keep halving, the squared points must again form opposite pairs. A large set of distinct real points cannot maintain this closure: real squares are nonnegative. Complex roots of unity supply the recursive pairing we need.
Complex numbers can. Take the eight points equally spaced around the unit circle: the eighth roots of unity, the numbers whose eighth power is one. They come in opposite pairs: rotating by half a turn negates a point. Squaring a point on the circle doubles its angle. Watch what happens to all eight: opposite points land together, and the eight become the four fourth roots of unity. Those four are again two opposite pairs. Square again: two points, plus one and minus one. Square once more, and everything lands on one. At every level the points pair up, exactly as the recursion needs. So evaluating at the n-th roots of unity takes two half-size evaluations plus linear work: n log n. That evaluation is the discrete Fourier transform, and this way of computing it is the fast Fourier transform.
The literal code uses a negative-angle forward root, matching NumPy's convention. For a nonempty power-of-two length, recursively transform even and odd coefficients, then combine each pair with one twiddle multiplication, an addition and a subtraction. Empty input returns empty; unsupported lengths are rejected. The inverse uses the opposite sign and divides by the transform length. With sufficient zero padding this computes a linear convolution in n log n arithmetic operations. Floating-point rounding and integer bit complexity are separate questions; a short arithmetic count is not an exactness proof.
6The FFT, II: butterfliesGraduate3 min
The fast Fourier transform, part two: butterflies. The FFT has a history of rediscovery. Gauss used an equivalent decomposition around 1805 in trigonometric interpolation; his notes appeared posthumously. In the early nineteen-sixties John Tukey described the decomposition in a scientific-advisory setting. Richard Garwin recognized its value for computing long Fourier transforms, including seismic analysis. James Cooley implemented the method, and their 1965 paper made it widely accessible. Heideman, Johnson and Burrus later documented Gauss's earlier work. The mathematics is the same recursive factorization, even when the application and implementation differ.
Unrolling the recursion gives a butterfly network. Here the inputs use bit-reversed order: binary zero-zero-one reverses to one-zero-zero. There are log-base-two n stages, each with n over two butterflies. A butterfly forms the sum and difference of one value and a twiddle-scaled partner. An iterative implementation can overwrite this array in place with little auxiliary storage. Our simple recursive Python implementation instead allocates slices and result arrays. The staged communication pattern also suits parallel implementations, though layout and synchronization costs still matter.
Why is the inverse so cheap? Write the transform as a matrix whose entries are powers of omega. Multiply a row of it by a conjugated row. If the rows are the same, every term is one and the sum is n. If not, the terms are the powers of some root of unity other than one, spread evenly around the circle, and they cancel to zero. So the matrix's inverse is its own conjugate divided by n, the rows are orthogonal, and transforming back is the same fast algorithm with omega replaced by its inverse. This orthogonality of characters is the algebraic heart of Fourier analysis, from Analysis, Built's ninth part to Part 53's quantum computers.
The operation counts and stopwatch measure different things. Direct DFT uses n squared coefficient products; radix-two FFT uses n over two times log-base-two n butterflies. Every complete timed output agrees with NumPy within the stated numerical tolerance. The large NumPy transforms also pass inverse-reconstruction and Parseval checks outside the timer. The table records the actual repeated timings on this host. Fourier transforms are central tools in signal processing, imaging and communications. Their usefulness does not imply that every codec or device uses this particular implementation.
7What the FFT multipliesIndustry3 min
An integer is a polynomial evaluated at the digit base. Three hundred and twenty-one has coefficients one, two and three in increasing powers of ten. Multiplying by four plus five x gives coefficients four, thirteen, twenty-two and fifteen. Carrying gives seventeen thousand three hundred and thirty-four, exactly three hundred and twenty-one times fifty-four. Our floating candidate groups four decimal digits per coefficient and zero-pads sufficiently to avoid circular aliasing. Conversion, transform, rounding and carry all belong to its end-to-end time. Each timed integer result is independently compared with exact multiplication.
A floating value's distance to the nearest integer is not its distance to the correct integer. The yellow column is only a rounding diagnostic: it could be small even if a coefficient were wrong by one. To certify these particular experiments, an independent native program computes every coefficient modulo two primes using exact integer transforms. Each rounded candidate is nonnegative and below an explicit coefficient bound, and the product of the primes is larger than that bound. Agreement in both residues therefore proves integer equality for every coefficient, including the zero padding. Reference construction and checks are outside the NumPy timer. This certifies these outputs, not all floating FFT multiplications at arbitrary lengths.
The number-theoretic transform makes the transform arithmetic exact. Choose a prime whose multiplicative group contains a root of the required power-of-two order. For this prime, three supplies suitable roots, and we check the length and root order. Butterflies then operate modulo the prime without rounding. Recovering unrestricted integer coefficients still requires a coefficient bound or enough moduli; modular exactness alone is not integer exactness. The decimal backend can use number-theoretic multiplication for large operands. Its complete-product timings here use the same fixed values as Python integers, with conversions excluded for both. Read the measured crossover from the table rather than extrapolating a fixed speed ratio.
Keep the complexity model attached to the timeline. School multiplication, Karatsuba and Toom-Cook reduce digit work. Schönhage and Strassen's 1971 ring-based transform gives a bit-complexity bound of n log n log log n; Fürer's later construction improves the asymptotic factor. Harvey and van der Hoeven proved an n log n bit-complexity upper bound in their 2019 work. This dated theorem is not a statement about the speed of our NumPy code or a survey of every later claim. Our million-decimal-place pi calculation uses exact binary splitting and certified final bounds. Its reported time belongs to this host and this implementation; the FFT-core measurement is a different experiment.
8The closest pairGraduate2 min
Given a million points, which two are closest? Comparing every pair is half a trillion distances. Michael Shamos and Dan Hoey's divide and conquer, from 1975: sort the points from left to right and split them at the median. Find the closest pair on each side, recursively. Call the smaller of the two distances delta. Any pair closer than delta must have one point on each side of the line. And both of its points must lie within delta of the line, in a thin strip.
The strip bound uses the recursive invariant, not the density of a typical picture. Maintain the points in y order by merging the two returned lists. Compare a point only with higher points less than delta away vertically. The candidate rectangle is two delta wide and delta high; split each half into four squares. Each square stays within one recursive half, where distinct points are at least delta apart. Its diagonal is smaller than delta, so it contains at most one point. Boundary and tie conventions must preserve that half assignment. At most seven successors remain besides the current point. Duplicates can instead certify distance zero immediately. Two half-size problems plus linear merging and strip work give n log n time.
For these fixed random inputs, count the actual distance evaluations. At a hundred thousand points, the implementation uses about a hundred and forty-two thousand distances instead of roughly five billion all-pairs candidates. Its observed strip maximum is two; the proof allows seven. Every timed result, including the largest case, is checked against SciPy's all-point nearest-neighbor query. Only the small all-pairs runs are timed; a large all-pairs time would be an extrapolation. Randomized grid methods can obtain expected linear bounds in suitable models with floor and hashing operations. That is a different guarantee from deterministic comparison-based divide and conquer.
9Dynamic programmingDegree2 min
The name is a piece of camouflage. In the 1950s Richard Bellman worked at the RAND Corporation on decisions taken in many stages. RAND was funded through the Air Force, and according to Bellman's autobiography the Secretary of Defense, Charles Wilson, had a horror of the word research, let alone mathematical. So Bellman chose programming, which then meant planning, as in a training programme, and dynamic, because, he wrote, it is impossible to use the word dynamic in a pejorative sense. The idea behind the name: an optimal plan is made of optimal plans for smaller problems, so solve the smaller problems first and remember the answers.
Fibonacci exposes repeated work. In the tree for F of five, the same smaller arguments recur on several branches. Naive recursion's call count grows exponentially; the exact count for F of thirty is shown in the table. Memoization keeps the first result for each argument. The counter includes calls that hit the cache, so F of thirty uses fifty-nine calls, not thirty arithmetic additions. Tabulation visits states from small to large and can retain only the last two values. Linear arithmetic work here assumes unit-cost addition; exact Fibonacci values grow in bit length.
A well-founded recurrence has a dependency graph. Draw edges from already smaller states to the states that use them. The state definition, such as an explicit stage index, makes this expanded graph acyclic even when the original problem has cycles. Tabulation evaluates it in topological order. Min-plus or max-plus recurrences with one predecessor choice describe shortest or longest paths. Fibonacci adds two answers, and tree knapsack can combine several child answers. Count work by summing the transition cost over all states. A uniform upper bound can be states times work per state; selecting a sufficient, compact state is the art.
10Edit distanceDegree2 min
Use unit-cost insertion, deletion and substitution. Levenshtein distance is the fewest such edits turning one string into the other. State D of i comma j compares the first i symbols with the first j. The empty-prefix boundaries are D of i comma zero equals i and D of zero comma j equals j. The final step deletes, inserts, or matches or substitutes the two last symbols. Take the minimum of the three corresponding predecessor costs; a match costs zero. There are n times m interior updates and n plus one times m plus one allocated table cells. These counts distinguish work from boundary storage.
Here is the table for intention and execution, a classic example. The first row and column count the cost of building a prefix from nothing. Every other cell takes the minimum of its three neighbours, so the table fills row by row, each cell ready when it is needed. The bottom-right corner holds the answer: five. To recover the edits themselves, walk back from the corner, each time to a neighbour that could have produced the value. Here the path runs down the diagonal: five substitutions, and the final four letters, t i o n, kept.
These complete edit tables are timed on fixed random DNA strings. Doubling both lengths quadruples the interior cell count; elapsed times need not scale by exactly four. Every timed distance and traceback is checked outside the timer against an independent rolling-row reference. Longest common subsequence uses a related recurrence with matches and skips, rather than the same unit-substitution objective. Insert-delete scripts connect that subsequence problem to file comparison; production diff tools use several algorithms and heuristics. Biological sequence alignment generalizes the scoring, including substitution scores and gap costs. The later conditional lower bound concerns exact worst-case distance, not every practical input, approximation or scoring model.
11Knapsack, and pseudo-polynomial timeDegree2 min
A thief with a knapsack that holds twelve kilograms faces six items, each with a weight and a value. The subproblem: the best value using only the first i items with capacity c. Either item i is left out, or it is taken, using up its weight. The table fills one item at a time; each row needs only the row above. The bottom-right cell is the answer, a hundred and ten, and tracing back through the cells where the value changed finds the items: weights three, two and seven, exactly filling the knapsack.
Why not be greedy? Take items in order of value per kilogram, as long as they fit. On our six items that gives a hundred and five, not a hundred and ten. On five hundred random sets of fifteen items it was wrong two times in five, once getting only seventy-eight percent of the best value. The independent sets here are not a matroid. If items could be cut, like gold dust, the same greedy would be exactly right: the fractional knapsack is a different, easier problem.
The dense table is polynomial in the numeric capacity W. These twenty-item instances multiply every weight and the capacity by the same scale, leaving the feasible subsets unchanged. An independent sparse-frontier calculation verifies their common optimum. We allocate n plus one rows of W plus one cells and update n times W plus one entries. Multiplying a number by ten adds about log-base-two ten bits to that number, while this table grows roughly tenfold. That is pseudo-polynomial: polynomial in a numeric magnitude, not its binary encoding length. The general exact optimization problem is NP-hard. A fully polynomial approximation scheme instead returns a near-optimum in time polynomial in the input size and the reciprocal accuracy parameter, under the usual positive-data assumptions.
12Matrix chains and optimal search treesGraduate2 min
Matrix multiplication is associative in exact arithmetic, but parenthesization changes the scalar work. A p-by-q matrix times a q-by-r matrix uses p q r scalar multiplications in the classical algorithm. For these six matrices, left-to-right costs forty thousand five hundred, and the worst of forty-two bracketings costs fifty-eight thousand. For each contiguous range, choose its final split and add the best left and right costs plus the final product cost. The recurrence enumerates these last-split choices. The optimum is fifteen thousand one hundred and twenty-five, with the bracketing shown. There are quadratically many ranges and at most linearly many splits each. Floating evaluation can also change rounding, and query-planning costs need richer models than this matrix example.
Here we model successful searches for ordered keys with nonnegative probabilities. We seek a binary search tree of minimum expected search depth; the key order must remain intact. The direct recurrence tries every root for every interval and sums the interval's probability mass. With the required monotonicity conditions and a consistent tie convention, optimal roots lie between the roots of neighboring intervals. Knuth's restricted ranges give quadratic total root trials, not a constant number for every interval. Both implementations are checked for equal costs. The table shows actual root-trial counts and separate timings. This optimization requires proof of the recurrence's structure; it does not apply to arbitrary dynamic programs.
13Dynamic programming on trees, graphs and sequencesGraduate2 min
A tree lets us combine independent subtrees. Each employee has a fun score, and a direct boss and report cannot both attend. This maximum-weight independent-set problem is hard on general graphs but has a simple tree recurrence. Store a take value and a skip value for every subtree. Taking a vertex forces each child to skip; skipping it lets each child choose its better state. An iterative postorder handles deep paths without raising the process recursion limit. The highlighted small-tree selection is checked by exhaustive search. The large-tree time covers the complete public iterative solver on two hundred thousand vertices, checked against a separate array recurrence; input generation is excluded.
Several graph algorithms use staged dynamic programming. Bellman-Ford limits the number of edges; Floyd-Warshall limits permitted intermediate vertices; Held-Karp records a visited subset and endpoint; DAG longest paths use a topological dependency order. These state spaces differ, so their costs differ even though all reuse smaller answers. Held-Karp has exponentially many subsets. Part eighteen's small checked example makes a dramatic improvement over tour enumeration without turning the problem polynomial. Its time is a measurement from that episode, not a new timing in this table.
Sequence models offer further examples. Viterbi chooses a maximum-probability path through a hidden-state trellis; it appears in communication decoding and speech models. For a fixed context-free grammar in the required normal form, CYK combines substring and grammar states; grammar size also matters when it is part of the input. Knuth optimization, divide-and-conquer optimization and convex-hull methods accelerate particular recurrences only when their structural hypotheses hold. They do not promise the same factor for every table. Memory can sometimes be reduced too: Hirschberg's divide-and-conquer reconstruction recovers an alignment in linear auxiliary space while preserving quadratic time in the general case.
14Backtracking and Dancing LinksDegree3 min
When no clever structure is known, we search. In 1848 the chess player Max Bezzel asked how to place eight queens on a chessboard so that none attacks another. Backtracking places one queen per row. In each row it tries the safe columns in turn; when a row has no safe column, it undoes the previous choice and moves that queen on. The power of the method is what it does not do: as soon as a partial placement fails, everything that would extend it is skipped. Here is the first solution found, and Franz Nauck showed in 1850 that there are ninety-two.
These counts enumerate all solutions, rather than stopping at the first. For eight queens the search visits two thousand and fifty-seven partial-placement nodes, including the root. The comparison n to the n counts complete row-by-row assignments, so the two columns count different objects. Pruning removes invalid branches but does not prove a polynomial worst-case algorithm. The table reports the actual node counts and elapsed times through fourteen queens, with solution totals checked against known values. A bitmask makes each safe-column operation cheap; it does not turn an exponential search tree into a linear one.
Exact cover chooses rows so every constraint column is covered exactly once. The small binary matrix makes that condition visible. Sudoku has up to seven hundred and twenty-nine candidate cell-digit rows and three hundred and twenty-four constraints, before givens filter candidates. Algorithm X chooses a column with fewest remaining options, tries a row and temporarily removes conflicts. Dancing Links unlinks a node by reconnecting its neighbors while retaining its own links. Restore in reverse order, and the original structure returns. Our solver now restores links even when a solution limit stops search early, so the same object can be solved again. Its update counter includes both cover and uncover pointer writes, excluding construction.
Here are three fixed Sudoku instances, including Inkala's 2012 puzzle with twenty-one givens. The two solvers' node counts refer to their own search procedures. Naive search stops at its first solution; Dancing Links searches until exhaustion or two solutions, allowing a uniqueness check. Both outputs satisfy every given, row, column and box. Fewest-options branching is a major part of the difference; the benchmark does not isolate it from representation and implementation. A count of one after exhaustive termination certifies uniqueness; a count capped at two means at least two, not an exact total. Generalized Sudoku hardness does not establish a worst-case bound from these three examples. Optimization search can add bounds to discard branches that cannot improve the incumbent, the subject of Part twenty-three.
15One problem, four paradigmsDegree2 min
Choose a nonempty contiguous subarray of maximum sum. The checked example highlights the first six values, totaling eighteen. Requiring nonempty matters: for an all-negative input the answer is the largest element, not zero. The problem arose in work on locating bright regions of digitized images. Bentley's Programming Pearls presents several algorithms for it. Comparing the same objective across these methods lets us see how reusing information changes the amount of work.
The four. Brute force tries every start and every end, and adds up each stretch: cubic. Keeping a running sum while the end moves avoids re-adding: quadratic. Divide and conquer, Michael Shamos's: the best stretch lies in the left half, in the right half, or across the middle, and the best crossing one is found by scanning outwards in linear time. n log n, the recurrence of the closest pair. And dynamic programming, found by the statistician Jay Kadane, as Bentley tells it, within a minute of hearing the problem at a seminar: the best stretch ending at each position is either the number there alone, or the best stretch ending one earlier, extended. One pass, four lines.
All executed methods use the same array at a given size. Cubic runs stop at four hundred elements; the million-element cubic number is an unexecuted growth-model projection, not a runtime measurement. Quadratic, divide-and-conquer and Kadane runs stop at the limits shown. Every timed answer agrees with a separate prefix-minimum formulation, checked after the stopwatch stops. Raw repeats and minima are recorded. The measured gaps depend on this implementation and host. The asymptotic difference follows from their work, not from fitting a few timing rows or assigning a hardware cause.
16Frontier: how fast can we multiply?Research3 min
Research barriers must name the method they restrict. Many exponent improvements analyze powers of Coppersmith-Winograd tensors through laser-method refinements. That is a family of constructions, not the definition of all matrix multiplication. Ambainis, Filmus and Le Gall's 2015 two-point-three-zero-seven-eight barrier concerns their specified generalized laser framework. Later universal-method results give other barriers for specified starting tensors. None is an unconditional lower bound of that size for matrix multiplication itself. New constructions, parameter choices and numerical optimization can improve upper bounds within the limits that actually apply. Our dated examples distinguish a proven method restriction from an unproved universal impossibility. Arithmetic exponent, input field, constants and practical crossover remain separate questions.
Now distinguish a conditional lower bound from a timing curve. SETH says that for every positive epsilon there is a clause width k for which k-SAT has no algorithm with a two-to-the-one-minus-epsilon-N exponential factor, apart from polynomial input factors. The hard width may depend on epsilon. Backurs and Indyk's reduction shows that a general exact edit-distance algorithm with a fixed truly subquadratic exponent would contradict this hypothesis, already for a fixed finite alphabet. Related reductions address LCS and dynamic time warping under their respective formulations. Approximate distance changes the task and has much faster guarantees in appropriate regimes. The diagram keeps hypothesis, reduction and conclusion separate.
Lower bounds also depend on the computational model. The standard FFT evaluates a linear transform in n log n arithmetic operations. That upper bound alone says nothing about all possible algorithms. Morgenstern's determinant argument gives an n log n lower bound in a bounded-coefficient linear-circuit model. Removing the coefficient restriction removes that proof's guarantee. Integer multiplication instead measures bit work; this course's NumPy convolution count is not such a lower bound. A method-specific theorem, a conjecture-based reduction and a general unconditional lower bound are different kinds of statements. Our research question asks about unrestricted linear arithmetic circuits for the DFT, with the field and allowed operations stated.
Use precise questions. What is the square matrix multiplication exponent over a specified field, and how do useful implementations compare once constants and input sizes are included? Can exact edit distance achieve a fixed truly subquadratic worst-case exponent, or can a suitable lower bound be proved without SETH? Must unrestricted linear arithmetic circuits over the complex numbers use n log n operations for the DFT? The bounded-coefficient theorem does not settle this broader model. Which objectives and independence structures support a particular greedy rule? Matroids answer a precise weighted-independent-set characterization, not every use of greedy reasoning. The starred exercise develops the circuit-model question; it has no supplied solution.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Greedy algorithms and the exchange argument; Huffman codes; matroids and the theorem that says exactly when greedy works. Karatsuba's three products and Strassen's seven. The fast Fourier transform, from the roots of unity to butterflies, and the multiplication of million-digit numbers. The closest pair. Dynamic programming, from Fibonacci through edit distance, knapsack, matrix chains, search trees and trees. Backtracking and dancing links. And one problem solved four ways.
Where this comes back. Part 20 adds randomness. Part 21 connects insert-delete scripts to paths on an edit graph and practical diff algorithms. Part 23 studies linear programming and branch and bound. Part 26 studies decision versions of knapsack and subset sum, and generalized Sudoku, as NP-complete problems. Part 27 develops conditional fine-grained hardness for exact worst-case edit distance. Part 30 uses big-integer arithmetic and modular transforms. Part 53 introduces the quantum Fourier transform, whose circuit and output access differ from a classical FFT.
In applications, the details return. Fourier-transform libraries serve signal processing, imaging and communications. Big-number libraries switch among school multiplication, Karatsuba, Toom-Cook and transform methods according to operand sizes and tuned thresholds. Matrix software combines layout, blocking, vectorization, threading and sometimes fast algebraic schemes. Diff and sequence alignment use related dynamic programs with different objectives and accelerations. Constraint and integer-programming solvers use search, propagation and bounds. The paradigm suggests a structure; correctness, numerical behavior and measurement scope still need checking.
The notes contain five worked exercises and a separate open research extension. Pause on any statement. The build exercise implements a number-theoretic transform for a five-hundred-digit product, with a transform length and coefficient bound that prevent modular ambiguity. Test it against an exact reference before comparing instruction counts; no crossover is promised in advance. The starred question asks about the unrestricted linear-circuit model and explains how it differs from the known bounded-coefficient result.
Next time, a fifth paradigm. A coin flip can stand in for cleverness: checking a matrix product in n squared time, finding a minimum cut by contracting random edges, testing primes in milliseconds, and counting the top words of the thirty novels in a few kilobytes, the ledger's ninth row. Part 20, Randomness as a Resource.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Insert and delete scripts return as paths in an edit graph in Part 21; branch and bound and linear programming in Part 23; knapsack, subset sum and generalized Sudoku as NP-complete problems in Part 26; the conditional lower bound for edit distance in Part 27; big-integer arithmetic and modular transforms in Part 30; the quantum Fourier transform in Part 53.
Key results
The part's results in one place, for revision.
Try it
Lab 19 · Three products, n log n butterflies, and one problem four ways
Count the digit products of school multiplication and of Karatsuba, and the butterflies of the FFT, against n^2, 3^lg n and (n/2) lg n; multiply by FFT and check every coefficient against the exact convolution; then run the four maximum-subarray algorithms on the same arrays.
python -m videos.cs.labs 19
needs numpy, scipy, matplotlib · download lab19.py ·
source on GitHub128 digits, school 16,384 digit products (n^2 = 16,384)
128 digits, Karatsuba 2,187 digit products (3^7 = 2,187)
1,024 points, FFT 5,120 butterflies ((n/2) lg n = 5,120; the definition: 1,048,576 products)
FFT product, 4,096 coefficients all exact; farthest from an integer before rounding: 3.1e-05
20,000 digits by FFT equal to Python's exact product
maximum subarray cubic, quadratic, divide and conquer and Kadane agree on 40 arrays
A better identity changes the exponent: 3^k leaves instead of 4^k, and (n/2) lg n butterflies instead of n^2 products. The small distance to an integer is a diagnostic, not a proof; the proof here is the comparison with the exact convolution.
The code (100 lines; it asserts its own result)
"""Lab 19: count Karatsuba's leaves and the FFT's butterflies, multiply by FFT, and solve one problem four ways."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import numpy as np
from explainer.cs.algo import paradigms as pd
TITLE = "Three products, n log n butterflies, and one problem four ways"
GOAL = ("Count the digit products of school multiplication and of Karatsuba, and the butterflies of the FFT, against "
"n^2, 3^lg n and (n/2) lg n; multiply by FFT and check every coefficient against the exact convolution; then "
"run the four maximum-subarray algorithms on the same arrays.")
TASKS = [
"Call pd.karatsuba with cutoff=32 and count again. How many digit products does the cutoff add at n = 128, and why is it still faster in wall-clock time?",
"Draw the digits from 0..9 instead of 1..9. The Karatsuba count drops below 3^k: find the line of school_mul that explains it.",
"Raise the chunk in the FFT experiment from 4 decimal digits to 6 and find the length at which a rounded coefficient is first wrong.",
]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. Karatsuba: 3^k digit products for two n = 2^k digit numbers, against the school method's n^2
ks = np.arange(1, 8)
school, kara = [], []
for k in ks:
n = 2 ** int(k)
a = [int(d) for d in rng.integers(1, 10, n)] # no zero digits: the school leaf skips a zero row
b = [int(d) for d in rng.integers(1, 10, n)]
cs, ck = [0], [0]
ps, pk = pd.school_mul(a, b, cs), pd.karatsuba(a, b, ck)
exact = pd.from_digits(a) * pd.from_digits(b)
assert pd.from_digits(ps) == exact and pd.from_digits(pk) == exact, "both multiply correctly"
school.append(cs[0])
kara.append(ck[0])
assert school == [4 ** int(k) for k in ks], "the school method does n^2 digit products"
assert kara == [3 ** int(k) for k in ks], "Karatsuba does 3^k digit products"
lab.row("128 digits, school", f"{school[-1]:,} digit products (n^2 = {128 * 128:,})")
lab.row("128 digits, Karatsuba", f"{kara[-1]:,} digit products (3^7 = {3 ** 7:,})")
# 2. the FFT: (n/2) lg n butterflies, the same numbers as the n^2 sum
fs = np.arange(1, 11)
flies = []
for k in fs:
n = 2 ** int(k)
x = list(rng.standard_normal(n) + 1j * rng.standard_normal(n))
c = [0]
y = pd.fft(x, c)
flies.append(c[0])
assert np.allclose(y, np.fft.fft(x), atol=1e-8), "the recursive FFT agrees with numpy"
if n <= 128:
d = [0]
assert np.allclose(pd.dft(x, d), y, atol=1e-7) and d[0] == n * n, "and with the n^2 definition"
assert np.allclose(pd.ifft(y), x, atol=1e-9), "the inverse is the conjugate transform over n"
assert flies == [(2 ** int(k) // 2) * int(k) for k in fs], "(n/2) lg n butterflies"
lab.row("1,024 points, FFT", f"{flies[-1]:,} butterflies ((n/2) lg n = {512 * 10:,}; the definition: {1024 ** 2:,} products)")
# 3. multiplying by FFT: every rounded coefficient against the exact integer convolution
ms, gaps = 2 ** np.arange(4, 13), []
for m in ms:
a, b = rng.integers(0, 10 ** 4, m), rng.integers(0, 10 ** 4, m) # four decimal digits per coefficient
n = 2 * int(m)
c = np.fft.irfft(np.fft.rfft(a.astype(float), n) * np.fft.rfft(b.astype(float), n), n)[:2 * m - 1]
gaps.append(float(np.abs(c - np.rint(c)).max()))
assert np.array_equal(np.rint(c).astype(np.int64), np.convolve(a, b)), "the rounded FFT is the convolution"
x = pd.from_digits([int(d) for d in rng.integers(0, 10, 19_999)] + [7])
y = pd.from_digits([int(d) for d in rng.integers(0, 10, 19_999)] + [3])
assert pd.fft_bigmul(x, y) == x * y, "a 20,000-digit product, exact"
p, q = [int(d) for d in rng.integers(0, 10, 64)], [int(d) for d in rng.integers(0, 10, 64)]
assert pd.poly_mul_fft(p, q) == pd.school_mul(p, q)[:127], "the series' own FFT, against the school product"
lab.row("FFT product, 4,096 coefficients", f"all exact; farthest from an integer before rounding: {gaps[-1]:.1e}")
lab.row("20,000 digits by FFT", "equal to Python's exact product")
# 4. one problem, four paradigms
for _ in range(40):
arr = [int(v) for v in rng.integers(-9, 10, int(rng.integers(1, 60)))]
answers = {pd.maxsub_cubic(arr), pd.maxsub_quadratic(arr), pd.maxsub_divide(arr), pd.maxsub_kadane(arr)}
assert len(answers) == 1, "the four algorithms agree"
assert pd.maxsub_kadane([-5, -2, -7]) == -2, "a nonempty answer: the largest element when all are negative"
lab.row("maximum subarray", "cubic, quadratic, divide and conquer and Kadane agree on 40 arrays")
lab.note = ("A better identity changes the exponent: 3^k leaves instead of 4^k, and (n/2) lg n butterflies "
"instead of n^2 products. The small distance to an integer is a diagnostic, not a proof; the proof "
"here is the comparison with the exact convolution.")
fig, ax = labs.figure(2, size=(11, 4.4))
n = 2.0 ** ks
ax[0].loglog(n, school, "o-", color=labs.RED, label="school: n²")
ax[0].loglog(n, kara, "o-", color=labs.GOLD, label="Karatsuba: 3^lg n = n^1.585")
ax[0].loglog(n, [3 * m * np.log2(2 * m) for m in n], "o-", color=labs.BLUE,
label="three FFTs of length 2n: 3n lg 2n butterflies")
ax[0].set(title="Multiplications to multiply two n-digit numbers", xlabel="digits n", ylabel="count")
ax[0].legend()
ax[1].loglog(ms, gaps, "o-", color=labs.GOLD, label="largest distance to an integer")
ax[1].axhline(0.5, color=labs.RED, ls="--", label="0.5: rounding could go wrong")
ax[1].set(title="Floating FFT convolution, base 10⁴: rounding margin", xlabel="coefficients per factor",
ylabel="|value − nearest integer|", ylim=(1e-9, 2))
ax[1].legend(loc=(0.04, 0.62))
lab.fig = fig
return lab
Now change it
- Call pd.karatsuba with cutoff=32 and count again. How many digit products does the cutoff add at n = 128, and why is it still faster in wall-clock time?
- Draw the digits from 0..9 instead of 1..9. The Karatsuba count drops below 3^k: find the line of school_mul that explains it.
- Raise the chunk in the FFT experiment from 4 decimal digits to 6 and find the length at which a rounded coefficient is first wrong.
Problems, with solutions
Try each problem before opening its solution.
Five worked exercises and an open research extension
-
Huffman's code. Prove that some optimal prefix code has the two rarest symbols as sibling leaves at the greatest depth, and deduce that Huffman's algorithm is optimal.
Solution
Assume at least two symbols with positive frequencies; empty and singleton alphabets are separate implementation conventions. Take an optimal code tree T; it is full (every internal node has two children), since otherwise a node with one child could be removed, shortening every code below it. Let a and b be sibling leaves at the greatest depth, and x and y the two rarest symbols. Swapping the leaves x and a changes the cost Σ f(s) d(s) by (f(x) − f(a))(d(a) − d(x)) ≤ 0, since f(x) ≤ f(a) and d(x) ≤ d(a). The same holds for swapping y and b. The result is still optimal, with x and y deepest siblings. For optimality, induct on the number of symbols. Replace x and y by one symbol z with f(z) = f(x) + f(y). Any tree T′ for the reduced alphabet gives a tree for the original one by hanging x and y below z, and its cost is cost(T′) + f(x) + f(y). By the lemma, some optimal tree has this form. So the original problem's optimum is the reduced problem's optimum plus f(x) + f(y). That is what Huffman computes: it merges x and y first and then, by induction, solves the reduced problem optimally.
-
Karatsuba. Solve T(n) = 3T(n/2) + cn, T(1) = 1, exactly for n = 2^k, and show that Karatsuba does exactly 3^k leaves in the full cutoff-one, uncarried, equal-power-of-two recursion tree. Explain why an implementation that skips zero products can execute fewer multiplications.
Solution
Unrolling, T(2^k) = 3^k T(1) + c Σ_{i=0}^{k−1} 3^i 2^{k−i} = 3^k + c 2^k Σ_{i<k} (3/2)^i = 3^k + c 2^k · 2((3/2)^k − 1) = (1 + 2c) 3^k − 2c 2^k. With 3^k = 3^{lg n} = n^{lg 3}, T(n) = (1 + 2c) n^{lg 3} − 2cn = Θ(n^{1.585}). Digit products happen only at the leaves. P(1) = 1, and each call makes three half-size calls and multiplies nothing itself, so the full-tree leaf count is P(2^k) = 3P(2^{k−1}) = 3^k. The implemented school leaf skips a zero left coefficient; the executed counter can therefore be smaller. The sums x₁ + x₀ have the same number of digits as the halves when digits are kept uncarried, as in
paradigms.karatsuba. With carrying they can gain one digit, so the exact leaf count need not survive that implementation change. The testtest_karatsuba_countchecks 3^k for k ≤ 7. -
Orthogonality. Prove Σ_{k=0}^{n−1} ω^{jk} = 0 for n ∤ j, where ω = e^{2πi/n}, and deduce F^{−1} = (1/n) F̄ for the DFT matrix F_{kj} = ω^{jk}.
Solution
If n ∤ j then ω^j ≠ 1, and the geometric sum is (ω^{jn} − 1)/(ω^j − 1) = (1 − 1)/(ω^j − 1) = 0. If n | j, every term is 1 and the sum is n. Now (F F̄)_{jl} = Σ_k ω^{jk} ω^{−lk} = Σ_k ω^{(j−l)k}, which is n when j = l and 0 otherwise (0 ≤ j, l < n, so n | j − l only when j = l). Hence F F̄ = nI and F^{−1} = F̄/n. Since F̄ is the DFT with ω replaced by ω^{−1} = ω̄, which is again a primitive n-th root of unity, the same FFT computes the inverse in O(n log n).
-
Edit distance. Prove the edit-distance recurrence correct, and recover an optimal edit script from the table in O(n + m) extra time.
Solution
Let D*(i, j) be the true distance between the prefixes a[1..i] and b[1..j]. In an optimal alignment of them, the last column is one of three things: a_i against a gap (a deletion), a gap against b_j (an insertion), or a_i against b_j (a substitution, free if they are equal). Removing that column leaves an alignment of the corresponding shorter prefixes, which must itself be optimal, or the whole could be improved. So D*(i, j) is the minimum of the three cases, which is the recurrence; with D(i, 0) = i and D(0, j) = j, induction on i + j gives D = D*. To recover a script, start at (n, m) and repeatedly move to a predecessor cell whose value plus the step's cost equals the current value; one always exists, because the current value was computed as such a minimum. Each move decreases i + j by one or two, so there are at most n + m moves, each O(1), and reading the moves backwards gives the edits.
-
Build: the NTT on Pebble. Implement the number-theoretic transform modulo p = 40961 = 5 · 2¹³ + 1 in the Pebble language, multiply two 500-digit numbers on the emulator, and compare its instruction count with Karatsuba.
Solution
Solution sketch. Use decimal-digit coefficients. Their convolution is at most 500 · 81 = 40,500 < p, so one residue identifies each integer coefficient. Here p is prime, 3 is a primitive root, and p² = 1,677,803,521 < 2³¹, so a product of residues fits the machine's positive signed range. Pad to 1,024 points; 1,024 divides p − 1. Use bit reversal and ten radix-two stages with stage root 3^((p−1)/length) mod p. Transform both inputs, multiply pointwise, inverse-transform using inverse roots, multiply by 1,024⁻¹ mod p, then carry in base ten. Normalize negative butterfly differences before using a language remainder operation. Three transforms use 15,360 butterflies; this is not an instruction count. Run the emulator to count instructions and compare with a stated Karatsuba cutoff on the same operands. Check both results against exact Python integers. Longer inputs require checking both transform divisibility and coefficient range again; additional primes and Chinese remaindering can increase the coefficient range, but do not guarantee a crossover.
-
★ Research (open): a DFT circuit lower bound. Over the complex numbers, consider exact linear arithmetic circuits whose gates form scalar multiples and sums of earlier values; count arithmetic operations, including scalar multiplications. Must every such circuit for the n-point DFT have Ω(n log n) operations when scalar coefficients are unrestricted?
Starting point, not a solution. Morgenstern's 1973 determinant argument establishes this scale in a bounded-coefficient model. Its coefficient restriction is part of the theorem. Compare the determinant growth allowed by one bounded gate with the DFT determinant magnitude. Then identify exactly where allowing arbitrarily large coefficients breaks that argument. Exhaustive searches over a finite coefficient set at n = 4 or 8 explore only that restricted set; they cannot settle the unrestricted question. Fixed-shape FFT operation counts are another, narrower optimization problem.
Notes and sources
Glossary
贪心算法 greedy algorithm · 交换论证 exchange argument · 区间调度 interval scheduling · 哈夫曼编码 Huffman code · 前缀码 prefix code · 拟阵 matroid · 独立集 independent set · 交换公理 exchange axiom · 图拟阵 graphic matroid · 分治 divide and conquer · Karatsuba 乘法 Karatsuba multiplication · Toom–Cook 乘法 Toom–Cook multiplication · 截断阈值 cutoff · 施特拉森算法 Strassen's algorithm · 矩阵乘法指数 matrix multiplication exponent · 激光法 laser method · 银河算法 galactic algorithm · 快速 傅里叶变换 fast Fourier transform · 离散傅里叶变换 discrete Fourier transform · 单位根 root of unity · 旋转因子 twiddle factor · 蝶形 butterfly · 位反转 bit reversal · 正交性 orthogonality · 卷积 convolution · 数论变换 number-theoretic transform · 最近点对 closest pair · 动态规划 dynamic programming · 记忆化 memoization · 制表法 tabulation · 编辑距离 edit distance · 最长公共子序列 longest common subsequence · 背包问题 knapsack problem · 伪多项式时间 pseudo-polynomial time · 矩阵链乘 matrix chain multiplication · 最优二叉搜索树 optimal binary search tree · 四边形不等式 quadrangle inequality · 树形动态规划 dynamic programming on trees · 回溯 backtracking · 精确覆盖 exact cover · 舞蹈链 dancing links · 分支定界 branch and bound · 最大子数组 maximum subarray · 强指数时间假设 strong exponential time hypothesis · 细粒度复杂性 fine-grained complexity · 刚性 rigidity
Sources
Canon. Books: Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, chapters 4, 14–15, 30; Kleinberg & Tardos, Algorithm Design, chapters 4–6; Dasgupta, Papadimitriou & Vazirani, Algorithms, chapters 2, 5–6; Knuth, The Art of Computer Programming, volume 2 §4.3.3 and volume 4B (Dancing Links); Bentley, Programming Pearls (1986), column 8; Bellman, Dynamic Programming (1957) and Eye of the Hurricane (1984); Oxley, Matroid Theory.
Papers: Whitney, "On the abstract properties of linear dependence" (1935); Huffman, "A method for the construction of minimum-redundancy codes" (1952); Rado (1957); Karatsuba & Ofman (1962); Toom (1963); Cook (1966); Cooley & Tukey, "An algorithm for the machine calculation of complex Fourier series" (1965); Levenshtein (1965); Strassen, "Gaussian elimination is not optimal" (1969); Needleman & Wunsch (1970); Edmonds, "Matroids and the greedy algorithm" (1971); Knuth, "Optimum binary search trees" (1971); Schönhage & Strassen (1971); Wagner & Fischer, "The string-to-string correction problem" (1974); Hirschberg (1975); Shamos & Hoey, "Closest-point problems" (1975); Ibarra & Kim (1975); Hunt & McIlroy (1976); Rabin (1976); Hitotumatu & Noshita (1979); Heideman, Johnson & Burrus, "Gauss and the history of the fast Fourier transform" (1984); Coppersmith & Winograd, "Matrix multiplication via arithmetic progressions" (1990); Kozen & Zaks, "Optimal bounds for the change-making problem" (1994); Knuth, "Dancing links" (2000); Fürer (2007); Harvey & van der Hoeven, "Integer multiplication in time O(n log n)" (2021); Fawzi et al., "Discovering faster matrix multiplication algorithms with reinforcement learning" (2022).
Frontier. Morgenstern (1973); Valiant, "Graph-theoretic arguments in low-level complexity" (1977); Impagliazzo & Paturi (2001); Cohn & Umans (2003); Johnson & Frigo, "A modified split-radix FFT with fewer arithmetic operations" (2007); Ambainis, Filmus & Le Gall, "Fast matrix multiplication: limitations of the Coppersmith–Winograd method" (2015); Backurs & Indyk, "Edit distance cannot be computed in strongly subquadratic time (unless SETH is false)" (2015); Abboud, Backurs & Vassilevska Williams (2015); Bringmann & Künnemann (2015); Alman & Vassilevska Williams, "Limits on all known (and some unknown) approaches to matrix multiplication" (2018); Afshani, Freksen, Kamma & Larsen, "Lower bounds for multiplication via network coding" (2019); Andoni & Nosatzki, "Edit distance in near-linear time: it's a constant factor" (2020); Duan, Wu & Zhou (2023); Alman, Duan, Vassilevska Williams, Xu, Xu & Zhou, "More asymmetry yields faster matrix multiplication" (2024).
Selected primary links (dates and models are part of each claim):
- Alman et al., April 2024 v1: ω < 2.371339; later versions have changed.
- Dupont et al., August 2026: selected optimization refinement, ω < 2.371177.
- Ambainis, Filmus and Le Gall: restrictions on specified laser frameworks.
- Backurs and Indyk: exact worst-case edit distance and SETH.
- Harvey and van der Hoeven, Annals 2021: O(n log n) bit operations; first announced in 2019.
- Fawzi et al., Nature 2022: the 47-product four-by-four example is over the field with two elements.
- Morgenstern, JACM 1973: bounded-coefficient linear complexity.
About this partfrom its README
Part 19 of the sixty-one-part course, Act IV, Algorithms. Greedy exchange,
divide and conquer, dynamic programming and pruned search are compared through executable instruments in
explainer/cs/algo/paradigms.py. The visual examples include interval schedules, a matroid exchange witness,
Strassen's block identities, roots of unity and a butterfly network, a closest-pair packing argument,
filled edit and knapsack tables, tree states, a binary exact-cover matrix, reversible links and a Kadane trace.
The episode distinguishes four kinds of evidence: a proved work bound, an observed counter or runtime, a model projection, and a research claim under stated hypotheses. The notes provide five worked exercises and one open research extension.
Chapter notes
- Hook: certified floor of π · 10^1,000,000. Adjacent Chudnovsky partial sums and integer square-root bounds give the same integer floor. The result has 1,000,001 digits including the initial 3. Complete Python, Decimal and floating FFT products use the same operands per row. The school estimate is extrapolated, and the separate FFT-core experiment excludes conversion and carry.
- Greedy and matroids: unweighted interval selection; finite coin-system experiments; Huffman coding; the nonnegative-weight greedy characterization of finite hereditary systems. Arbitrary signed weights require omitting negative elements when any independent set is allowed. Descending forest greedy maximizes weight; ascending Kruskal minimizes it. Nonnegative greedy matching is a one-half approximation.
- Divide and conquer: Karatsuba's coefficient model and measured cutoffs; Strassen's seven products; FFT evaluation, inverse orthogonality and padding; closest-pair merging and at most seven strip successors. Strassen's additions summed across the tree have the same exponent as its leaf products. Extended-precision reference disagreement is approximate, not a certified true error. The matrix-exponent plot selects dated 2024 and August 2026 upper bounds; it is not a latest-record survey or a crossover measurement.
- Convolution certification: the ten-million-digit-equivalent FFT-core case checks all 4,999,999 coefficients and all padded zeros against two independent native integer NTTs. Each candidate and true coefficient lies in [0, B], where B = min(|A|, |B|) max(A) max(B) is smaller than the two-prime product. Equal residues therefore imply equal integer coefficients. A small distance to the nearest integer alone does not establish correctness. Reference construction, compilation and validation are outside the timer.
- Dynamic programming: Fibonacci calls versus arithmetic and bit length; dependency graphs with either choice or combination; edit-distance boundaries, interior updates and traceback; knapsack numeric capacity versus encoding length; matrix-chain bracketings and conditional Knuth optimization. The six-matrix example has 42 orders, optimum 15,125, left-to-right 40,500 and worst 58,000 scalar products. Tree timing covers the complete iterative public solver on 200,000 vertices, with input generation excluded.
- Search and maximum subarray: queens partial nodes versus complete assignments; Algorithm X and restored Dancing Links, including early returns; Sudoku constraints and uniqueness. Naive Sudoku stops at its first solution while DLX exhausts search or stops at two, so their node counts measure different work. All maximum-subarray methods require a nonempty result; all-negative input returns its largest element.
- Frontier: method-specific matrix multiplication barriers, exact worst-case edit distance conditional on SETH, and bounded-coefficient versus unrestricted complex linear circuits for the DFT. Arithmetic operations and integer bit complexity use different models.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Greedy: interval scheduling by earliest finish, proved by exchange; four rules on 2,000 random instances with counterexamples; coins {1, 3, 4} and Kozen–Zaks; Huffman's code on the corpus's 27 symbols (4.12 bits against an entropy of 4.08).
- Matroids: Whitney's axioms; the Rado–Edmonds greedy theorem (proved); forests (Kruskal) optimal 400 of 400, matchings 248 of 400 (never below half).
- Karatsuba (1960), which refuted Kolmogorov's n² conjecture: 1234 × 5678 by three products; the recursion tree; measured in Python (pure Karatsuba loses below 4,096 digits; with a 32-digit cutoff it wins from 64); CPython's cutoff; Toom–Cook.
- Strassen (1969): the seven products; exact operation counts; the history of ω from 2.807 to 2.3713 (Alman, Duan, Vassilevska Williams, Xu, Xu & Zhou 2024); galactic algorithms; against numpy's BLAS (3–5× slower, 10× rounding error); AlphaTensor (callback to AI, Built 26).
- The FFT, I: coefficients against values; ± pairs; the roots of unity squaring onto half as many points (the centerpiece animation); the algorithm in ten lines.
- The FFT, II: Gauss (c. 1805) and Cooley–Tukey (1965); the butterfly network and bit reversal; the inverse by orthogonality (proved); DFT against FFT in Python (272× at 2,048 points); numpy.
- Multiplication by FFT: integers as polynomials; floating-point exactness measured to ten million digits; the
NTT modulo 119 · 2²³ + 1 (Part 30) and Python's
decimal; Schönhage–Strassen to Harvey & van der Hoeven's n log n (2019). - Closest pair in the plane: the strip argument with at most seven neighbours (proved); 100,000 points in 1.3 s.
- Dynamic programming: Bellman (1957) and the story of the name; Fibonacci's call tree; memoization against tabulation; DP as paths in a DAG of subproblems.
- Edit distance (Wagner–Fischer), the intention/execution table and traceback; LCS,
diff(Parts 21, 41), Needleman–Wunsch. - Knapsack's O(nW) table; greedy by value per weight fails; the same problem with ever larger numbers (pseudo-polynomial time); NP-hardness (Part 26) and Ibarra–Kim's approximation scheme.
- Matrix chains (15,125 against 58,000 worst); optimal BSTs and Knuth's O(n²) speedup (33× fewer steps at 200 keys).
- DP on trees (independent sets, 200,000 vertices in 0.3 s), on graphs (Bellman–Ford, Floyd–Warshall, Held–Karp, DAG paths) and on sequences (Viterbi, CYK, speedups, Hirschberg).
- Backtracking and branch-and-bound: n-queens (2,057 nodes for eight); Sudoku as exact cover with Dancing Links (Knuth 2000) against plain backtracking on three puzzles.
- One problem, four paradigms: maximum subarray by brute force O(n³), running sums O(n²), divide and conquer O(n log n), and Kadane's DP O(n), timed to a million numbers.
- Frontier: the limits of the laser method (Ambainis, Filmus & Le Gall 2015; Alman & Vassilevska Williams 2018); edit distance and SETH (Backurs & Indyk 2015) and its approximation (Andoni & Nosatzki 2020); lower bounds for the FFT and multiplication (Morgenstern 1973; Afshani et al. 2019); open problems. Outro.
Computed: every number above, in videos/cs/cs19/compute.py with explainer/cs/algo/paradigms.py (tested in
tests/test_cs19_paradigms.py): a million digits of π by Chudnovsky's series; four multipliers on million-digit
numbers; Karatsuba against school; Strassen's counts, time and error; DFT against FFT; FFT exactness; closest pair;
DP tables; Dancing Links on Sudoku; maximum subarray four ways.
Visuals: the roots of unity squaring onto half as many points; butterflies; Strassen's seven products coloured;
DP tables with traceback; the exchange argument as swapped bars; the matroid exchange on a graph; queens and
dancing links.
In practice: diff tools, bioinformatics, the FFT in audio, images and radios, GMP and BLAS, dynamic programming in
pricing and scheduling, SAT and constraint solvers.
Reading: CLRS ch. 4, 14–15, 30; Kleinberg & Tardos ch. 4–6; Dasgupta, Papadimitriou & Vazirani, Algorithms ch. 2,
5–6; Knuth, TAOCP 2 §4.3.3 and 4B; Bentley, Programming Pearls; Cooley & Tukey 1965; Strassen 1969; Karatsuba &
Ofman 1962; Harvey & van der Hoeven 2021; Bellman 1957; Edmonds 1971; Alman et al. 2024.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
哈夫曼编码。 证明存在一个最优前缀码,使两个最稀有的符号是最大深度处的兄弟叶子,并由此推出哈夫曼算法是最优的。
解答
假设至少有两个正频率符号;空字母表和单符号情况另按实现约定处理。取一棵最优编码树 T;它是满的(每个内部结点都有两个孩子),否则只有一个孩子的结点可以去掉,使其下所有编码变短。 设 a、b 是最大深度处的兄弟叶子,x、y 是两个最稀有的符号。交换叶子 x 和 a,代价 Σ f(s) d(s) 改变 (f(x) − f(a))(d(a) − d(x)) ≤ 0,因为 f(x) ≤ f(a) 且 d(x) ≤ d(a)。交换 y 和 b 同理。结果仍是最优的,且 x、y 是最深的兄弟。 关于最优性,对符号数归纳。把 x 和 y 换成一个符号 z,f(z) = f(x) + f(y)。缩小后字母表的任意一棵树 T′,把 x 和 y 挂在 z 下面,就得到原字母表的一棵树,代价为 cost(T′) + f(x) + f(y)。由引理,某棵最优树具有这种形式。所以原问题的最优值等于 缩小问题的最优值加 f(x) + f(y)。哈夫曼算法算的正是这个:它先合并 x 和 y,再由归纳假设最优地解决缩小后的问题。
-
Karatsuba。 对 n = 2^k 精确求解 T(n) = 3T(n/2) + cn,T(1) = 1,并在等长、二次幂长度、不进位且截断为 1 的模型下,证明完整递归树有 3^k 个叶子;解释跳过零乘法时实际计数为何可能更小。
解答
展开得 T(2^k) = 3^k T(1) + c Σ_{i=0}^{k−1} 3^i 2^{k−i} = 3^k + c 2^k Σ_{i<k} (3/2)^i = 3^k + c 2^k · 2((3/2)^k − 1) = (1 + 2c) 3^k − 2c 2^k。由于 3^k = 3^{lg n} = n^{lg 3},T(n) = (1 + 2c) n^{lg 3} − 2cn = Θ(n^{1.585})。数字乘法只发生在叶子上。P(1) = 1,每次调用做三次半规模调用、自己不做乘法,所以 完整树的叶子数为 P(2^k) = 3P(2^{k−1}) = 3^k。实现会跳过左系数为零的叶子乘法,因此实际乘法次数可能更小。 如
paradigms.karatsuba那样不进位地保存数字时,和 x₁ + x₀ 与两半的位数相同。进位时可能多一位,此时不能照搬精确的叶子数公式。测试test_karatsuba_count对 k ≤ 7 检验了 3^k。 -
正交性。 设 ω = e^{2πi/n},证明当 n ∤ j 时 Σ_{k=0}^{n−1} ω^{jk} = 0,并推出 DFT 矩阵 F_{kj} = ω^{jk} 满足 F^{−1} = (1/n) F̄。
解答
若 n ∤ j,则 ω^j ≠ 1,几何级数之和为 (ω^{jn} − 1)/(ω^j − 1) = (1 − 1)/(ω^j − 1) = 0。若 n | j,每一项都是 1,和为 n。 于是 (F F̄)_{jl} = Σ_k ω^{jk} ω^{−lk} = Σ_k ω^{(j−l)k},当 j = l 时为 n,否则为 0(0 ≤ j, l < n,所以只有 j = l 时 n | j − l)。 因此 F F̄ = nI,F^{−1} = F̄/n。F̄ 是把 ω 换成 ω^{−1} = ω̄ 的 DFT,而 ω̄ 也是本原 n 次单位根,所以同一个 FFT 能在 O(n log n) 内算出逆变换。
-
编辑距离。 证明编辑距离递推式正确,并在 O(n + m) 额外时间内从表中恢复一个最优编辑脚本。
解答
设 D*(i, j) 是前缀 a[1..i] 与 b[1..j] 之间的真实距离。在它们的一个最优对齐中,最后一列只有三种情况:a_i 对空位 (删除)、空位对 b_j(插入),或 a_i 对 b_j(替换,相等时免费)。去掉这一列,剩下的是相应较短前缀的一个对齐,它本身必须最优, 否则整体还能改进。所以 D*(i, j) 是三种情况的最小值,这就是递推式;加上 D(i, 0) = i、D(0, j) = j,对 i + j 归纳即得 D = D*。 要恢复脚本,从 (n, m) 出发,反复移到一个前驱格子,使其值加上这一步的代价等于当前值;这样的前驱总存在,因为当前值正是作为这样的 最小值算出来的。每一步让 i + j 减少一或二,所以至多 n + m 步,每步 O(1),倒过来读就是编辑操作。
-
动手:在 Pebble 上实现 NTT。 用 Pebble 语言实现模 p = 40961 = 5 · 2¹³ + 1 的数论变换,在模拟器上做两个 500 位数的乘法, 并与 Karatsuba 比较指令数。
解答
解答提要。 采用十进制数字系数,每个卷积系数至多 500 · 81 = 40,500 < p,故一个模数足以唯一恢复整数系数。 p 是素数,3 是其原根;p² = 1,677,803,521 < 2³¹,余数乘积可装入正的有符号范围。 补零到 1,024 点,因 1,024 整除 p−1。位反转后做十级蝶形,每级使用根 3^((p−1)/length) mod p。 变换两个输入,逐点相乘,以逆根作逆变换,再乘 1,024 的模逆,最后十进制进位。 蝶形差为负时先归一化,再使用语言的取余操作。三次变换共 15,360 个蝶形;蝶形数不等于指令数。 在同一操作数上运行模拟器,比较指定截断的 Karatsuba,且先用 Python 精确整数核验。 扩大输入时需重新检查变换长度整除条件与系数范围;多素数及中国剩余定理能扩大范围,但不保证实用交叉点。
-
★ 开放研究题:DFT 电路下界。 在复数域上,考虑精确线性算术电路,每个门由此前值做标量乘法或加法, 标量乘法也计入算术操作。系数不受限时,n 点 DFT 是否仍需 Ω(n log n) 次操作?
起点,并非解答。 Morgenstern(1973年)的行列式论证针对有界系数模型;系数限制是定理条件。 比较单个有界门能带来的行列式增长与 DFT 行列式的大小,再指出任意大系数为何破坏该论证。 对 n=4 或 8、有限系数集的穷举只探索受限模型,不能解决一般问题。固定 FFT 形状下的运算数优化也更狭窄。
Build the film
python -m videos.cs.cs19.compute # the part's numbers, into .cache/cs19
python tools/build.py cs19 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs19 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs19. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build itBuild and measurement protocol
python -m videos.cs.cs19.compute # rebuild all numerical payloads
python tools/build.py cs19 -q l # 480p preview
python tools/build.py cs19 # 1080p production build
Schema-2 caches record raw timed trials, repeat counts, minima, Python/NumPy versions, NumPy build metadata,
and the queried BLAS thread configuration. Every timed output is validated after its timer stops.
Measurements describe one shared host. They do not isolate hardware causes or establish universal winners.
Random seeds, operand hashes where used, full references and work-count definitions are in compute.py
and measurements.py. Floating FFT integer multiplication is an experimental candidate checked against
an exact product for the measured instances; a supported chunk width is not a universal rounding guarantee.
The on-screen ten-line FFT is the radix-two core for a nonempty power-of-two input. The public Python
instrument additionally returns an empty result for empty input and rejects unsupported lengths.