Selected Topics: What This Course Covers
The first five courses of this track built a toolkit: asymptotic analysis and recurrences, sorting and selection, data structures, dynamic programming and greedy algorithms, and graph algorithms. This last course of Part I applies that toolkit to seven topics that each open a field of their own. Some are about new models (many processors at once, inputs that arrive one piece at a time), some about new domains (matrices, polynomials, numbers, strings), and the last is about the limits of efficient computation: NP-completeness.
Like the rest of the track, the course follows the topic order of Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein (Part VII, "Selected Topics", together with the chapter on online algorithms of its fourth edition), with every explanation, example, figure and exercise written from scratch. Good companions are Algorithm Design by Kleinberg and Tardos for NP-completeness and its reductions, Algorithms by Dasgupta, Papadimitriou and Vazirani for the FFT and number-theoretic algorithms, Gusfield's Algorithms on Strings, Trees and Sequences for string matching, and Garey and Johnson's Computers and Intractability for a catalogue of NP-complete problems.
Seven topics in one program
Each section of the course replaces an obvious algorithm by a much better one, or proves that no much better one is likely to exist. The program below gives a taste of four of them, counting basic steps as everywhere in this track.
import cmath
from itertools import permutations
# 1. Parallelism: the sum of 2^20 numbers has work about 3n but a critical path of only 41 steps
n = 2 ** 20
print(f"parallel sum of {n} numbers: work {3 * n - 2}, span {2 * 20 + 1}")
# 2. Polynomials: multiplying two polynomials with 1024 coefficients
m = 1024
print(f"polynomial product, {m} coefficients: schoolbook {m * m} multiplications, "
f"FFT about {3 * (2 * m) // 2 * 11 + 2 * m} (three transforms of length {2 * m} plus pointwise)")
# 3. Strings: searching for a^99 b in a^5000
T, P = "a" * 5000, "a" * 99 + "b"
naive = sum(min(len(P), next((j + 1 for j in range(len(P)) if T[s + j] != P[j]), len(P)))
for s in range(len(T) - len(P) + 1))
print(f"naive search: {naive} comparisons; KMP: at most {2 * len(T)}")
# 4. NP-completeness: checking a tour is fast, finding the best one by brute force is not
cities = 9
print(f"one tour of {cities} cities is checked in {cities} steps; brute force tries "
f"{len(list(permutations(range(1, cities))))} tours")parallel sum of 1048576 numbers: work 3145726, span 41
polynomial product, 1024 coefficients: schoolbook 1048576 multiplications, FFT about 35840 (three transforms of length 2048 plus pointwise)
naive search: 490100 comparisons; KMP: at most 10000
one tour of 9 cities is checked in 9 steps; brute force tries 40320 tours
One more taste, from the online section: renting skis costs 1 per day and buying costs 10, but nobody knows how long the season lasts. The "break-even" rule (rent for 9 days, then buy) never pays more than times what someone who knew the future would pay, whatever the season, while buying at once can cost 10 times too much (if the season lasts one day) and always renting gets worse without limit as the season grows (10 times too much at 100 days).
B = 10
rules = {"buy at once": lambda D: B, "always rent": lambda D: D,
"break-even": lambda D: D if D < B else (B - 1) + B}
for name, cost in rules.items():
worst = max(cost(D) / min(D, B) for D in range(1, 101))
print(f"{name:12}: worst ratio to the optimum over seasons of 1..100 days = {worst:.1f}")buy at once : worst ratio to the optimum over seasons of 1..100 days = 10.0
always rent : worst ratio to the optimum over seasons of 1..100 days = 10.0
break-even : worst ratio to the optimum over seasons of 1..100 days = 1.9
What the course covers
| Section | Problems and algorithms | Main results |
|---|---|---|
| Parallel algorithms | fork-join model, parallel loops, parallel merge sort | work and span laws; greedy scheduling within ; races; merge sort with span |
| Online algorithms | paging, ski rental, list update | competitive ratio; LRU is -competitive; break-even is -competitive, randomized ; move-to-front is 2-competitive |
| Matrices and linear programming | Strassen recap, LU and LUP decomposition, inversion, LP formulations | factorization and solves; inversion as hard as multiplication; shortest paths and flows as LPs |
| Polynomials and the FFT | DFT, recursive and iterative FFT, number-theoretic transform | polynomial and integer multiplication in |
| Number-theoretic algorithms | Euclid, modular exponentiation, Miller-Rabin, RSA | Lamé's theorem; exponentiation; error at most |
| String matching | naive, Rabin-Karp, automata, KMP, suffix arrays | matching; queries on an indexed text |
| NP-completeness | P, NP, reductions, Cook-Levin, SAT, 3-CNF-SAT, clique, vertex cover, Hamiltonian cycle, TSP, subset sum | the reduction chain from circuit satisfiability; approximation as a way out |
The sections are largely independent. The number-theory lessons are bridge lessons: they take the running-time view only and link to Number Theory & Cryptography for the mathematics. Likewise the LP lessons formulate problems and leave the simplex method and duality to Optimization and to the Part II course Linear Programming & Duality for Algorithms. The online-algorithms section is a first look at Online Algorithms & Competitive Analysis, and the last NP lesson a preview of Approximation Algorithms.
Conventions
- Pseudocode follows the track's conventions (How to read pseudocode): arrays are 0-based and
for i = 1 to nincludes both ends. Parallel pseudocode addsspawn,syncandparallel for. - is . Costs are counted in basic steps (strands, comparisons, multiplications, table entries), never timed, so the numbers you see when you run an example are exactly the ones in the text.
- Every algorithm comes with a Python version, and the core algorithms also with a C++20 version. Compiler Explorer, which runs the C++ examples, cannot start threads, so the parallel lessons simulate parallel execution by building and measuring computation DAGs; the results are deterministic. Reductions and analyses stay in Python. Random choices use a fixed seed, and floating-point results (in the FFT) are rounded before printing so every run prints the same digits.
- The animations of Rabin-Karp, KMP and paging and the labs for ski rental and linear programming are produced by running the real algorithm; next to each one, a Python program prints the same steps.
What you should know first
The course assumes the earlier courses of the track, especially Foundations of Algorithm Analysis (recurrences and the master theorem, used for the FFT and the parallel algorithms), Design Techniques (the potential method, used for move-to-front and KMP; the knapsack DP, used for subset sum) and Graph Algorithms (shortest paths, flows and spanning trees, used in the LP and NP lessons). Complex numbers are needed for the FFT; Complex Numbers is a quick refresher.
The course has practice problems in the practice area: Find Every Occurrence (KMP), Fast Modular Exponentiation, Subset Sum, Count Cache Misses, and the older Greatest Common Divisor, Prime Check, Sieve of Eratosthenes and Matrix Multiplication. Each lesson links to the ones it prepares you for.
Test yourself
Which question does the NP-completeness section of this course answer?
- How to sort in linear time
- Which problems are as hard as every problem in NP, so that a fast algorithm for one would give fast algorithms for all
- How to prove P = NP
- How to multiply matrices faster
Why do the parallel-algorithm lessons simulate parallelism instead of running threads?
- Python cannot do arithmetic in parallel
- The online compiler cannot start threads, and measuring work and span of a computation DAG gives deterministic, machine-independent numbers
- Parallel algorithms are always slower
- Threads are not part of C++
How much faster asymptotically is FFT-based polynomial multiplication than the schoolbook method?
- A constant factor
- versus
- versus
- It is slower