Module 08

Algorithms and Computational Complexity

How can we solve problems correctly while using as few computational resources as possible?

lessons
33
duration
59 h 10 min
concepts
222
available in English
33 / 33
completed by you
0 of 33

Where it fits

Overview

A specialist course in algorithm design and analysis: cost models and asymptotic, amortized, expected and high-probability analysis; advanced data structures including heaps, universal and cuckoo hashing, balanced and self-adjusting trees, B-trees, union-find, tries, suffix arrays and the FM-index; divide and conquer, greedy algorithms and matroids, and dynamic programming and its optimizations; graph algorithms through flows, matchings and minimum-cost flow; randomization, streaming, online and parallel algorithms. The second half develops complexity theory, including P, NP, Cook-Levin, reductions, PSPACE, #P, ETH and fine-grained complexity, and practical responses to NP-hardness through exact, parameterized and approximation algorithms and their limits, including PCP and Unique Games. Each algorithm is animated step by step, proved, implemented from scratch in Python and checked against networkx, SciPy and OR-Tools.

Why it matters

This is the language used to reason about computational cost throughout the curriculum, from topological ordering in PyTorch's backward pass and dynamic programming in Viterbi, CTC and MDPs to parallel scans in state-space models, hashing and sketches for LLM data deduplication, Hungarian matching in DETR and radix-tree prefix caching. Application security uses these tools to understand algorithmic complexity attacks such as hash flooding and ReDoS, Aho-Corasick signature matching, flows and minimum cuts in call graphs, and when an exact analysis is NP-hard and calls for approximation with guarantees. The module concludes with research frontiers including algorithms with predictions, near-linear-time maximum flow and AI-discovered algorithms such as AlphaTensor, AlphaDev, FunSearch and AlphaEvolve.

Lessons 33

  1. 01Cost models and asymptotic analysis of algorithmsA detailed review of efficient algorithms, including RAM and word-RAM models, input size in bits, worst and average cases, and space complexity. Apply O, Ω and Θ to cost functions, compare theory with doubling experiments and log-log plots, and examine algorithmic complexity attacks where worst cases can cause denial of service.Review80 min
  2. 02Binary search and comparison sortingA rigorous review of classical searching and sorting algorithms, focusing on the invariants that make them correct. Study binary search with half-open intervals, binary search on the answer, exponential search, insertion sort, mergesort, stability and linear-time sorting. Prove the Ω(n log n) comparison-sorting lower bound and see why counting sort and radix sort can avoid it.Review85 min
  3. 03Divide and conquer and the master theoremStudy divide and conquer as a source of algorithms and recurrences. Prove the master theorem with recursion trees, introduce Akra-Bazzi for unequal splits, and apply these tools to Karatsuba, Strassen, closest pair and inversion counting. Conclude with the matrix multiplication exponent ω and its current state.Core110 min
  4. 04Quicksort, selection and Las Vegas algorithmsA first look at randomization as a design tool. Analyze randomized quicksort with indicator variables and obtain its expected 2n ln n comparisons. Study three-way partitioning, quickselect's expected linear selection time, and median-of-medians worst-case linear time. Distinguish Las Vegas and Monte Carlo algorithms and see these ideas combined in introsort, pdqsort and CPython's adaptive mergesort.Core100 min
  5. 05Amortized analysisMany data structures have occasionally expensive operations that are cheap in aggregate. Study the aggregate, accounting and potential methods on dynamic arrays, binary counters, multipop stacks and two-stack queues; prove why shrinking requires hysteresis; and use deamortization for worst-case bounds when latency matters.Core90 min
  6. 06Priority queues and heapsPriority queues power Dijkstra, Prim, Huffman, schedulers and top-k. Implement a binary heap in an array, prove linear-time construction, add decrease-key with a position index, and study d-ary, meldable and Fibonacci heaps with potential analysis.Core105 min
  7. 07Hashing: tables, universality and adversariesHash tables are programming's most widely used data structure, and their analysis requires randomness. Study chaining and open addressing, including linear probing and Robin Hood hashing; Carter-Wegman universal hashing and k-wise independence; cuckoo hashing; and FKS perfect hashing. Finish with hash-flooding attacks, SipHash, and the design of CPython dictionaries.Core115 min
  8. 08Balanced search trees and B-treesBinary search trees maintain ordered sets with search, insertion, predecessor and range queries. Study rotations, AVL and red–black trees as 2–3–4 trees, external-memory costs and optimal B-trees, and parameter-free cache-oblivious design.Core115 min
  9. 09Treaps, skip lists and splay treesBalance without color rules through randomized treaps and skip lists or self-adjusting splay trees. Prove the access lemma, examine working-set and dynamic-optimality results, and introduce persistence by path copying.Advanced105 min
  10. 10Range query data structuresBuild a range-query toolkit: prefix sums, Fenwick and segment trees, lazy propagation, sparse tables, LCA and augmented trees.Advanced105 min
  11. 11Union-find and the inverse Ackermann functionAnalyze union-find, rank and path compression, inverse Ackermann bounds, and incremental and offline connectivity.Core90 min
  12. 12Tries, automata and pattern matchingSingle- and multipattern text matching underpin antivirus software, intrusion detection and code scanning. Study tries and radix trees, KMP's prefix function, Rabin-Karp rolling hashes, and Aho-Corasick matching of thousands of patterns in linear time. Compare backtracking regex engines with automaton simulation and examine their connection to ReDoS.Core110 min
  13. 13Suffix arrays, LCP and the FM-indexConstruct suffix arrays and LCP, relate them to suffix trees, and search a Burrows-Wheeler transform using an FM-index.Advanced110 min
  14. 14Greedy algorithms, exchange arguments and matroidsProve and refute greedy algorithms using stays-ahead and exchange arguments, then characterize optimal greedy selection with matroids.Core100 min
  15. 15Dynamic programming: principles and sequence problemsDevelop dynamic programming from subproblem DAGs through LIS, knapsack, edit distance and Hirschberg reconstruction.Core115 min
  16. 16Dynamic programming over intervals, trees and subsetsBuild interval, tree and subset dynamic programs, including matrix-chain ordering, CYK, rerooting and Held–Karp.Advanced115 min
  17. 17Advanced dynamic programming: semirings and speed-upsUnify dynamic programs with semirings and accelerate transitions using monotone queues, convex hulls, divide and conquer, Knuth–Yao and SMAWK.Advanced115 min
  18. 18Depth-first search, topological sort and componentsBuild linear graph traversals, topological orders, strongly connected components, bridges and articulation points, with proofs and practical representations.Core105 min
  19. 19Shortest pathsStudy shortest paths through relaxation, from DAGs and Dijkstra to Bellman–Ford, Floyd–Warshall and Johnson, including recent complexity results.Core115 min
  20. 20Minimum spanning treesProve the cut and cycle properties, build minimum spanning trees with Kruskal, Prim and Borůvka, and apply them to clustering and approximation.Core90 min
  21. 21Maximum flow and minimum cutNetwork flow is a powerful modeling tool: matching, disjoint paths, image segmentation, project selection and vulnerability cuts in code graphs reduce to it. Prove max-flow min-cut with augmenting paths, analyze Edmonds–Karp and Dinic, and introduce push–relabel. Half the lesson teaches modeling problems as flows.Advanced120 min
  22. 22Matchings, assignment and minimum-cost flowMatching is a widely applied combinatorial problem: assigning tasks, matching DETR predictions to objects, or doctors to hospitals. Study bipartite augmenting paths and Hopcroft–Karp, assignment with the Hungarian algorithm and duality, minimum-cost flow with successive shortest paths and potentials, Edmonds' blossoms for general graphs, and Gale–Shapley stable matching.Advanced120 min
  23. 23Randomized algorithm techniquesRandomness produces simpler, faster or the only known algorithms. Study Karger and Karger–Stein min-cut, Freivalds verification and Schwartz–Zippel polynomial identity testing, probability amplification, balls and bins with the power of two choices, the probabilistic method and derandomization by conditional expectations.Advanced115 min
  24. 24Streaming algorithms and sketchesWhen data passes once and does not fit in memory, answer using sublinear summaries. Study the streaming model, reservoir sampling, Misra–Gries heavy hitters, Bloom filters, count-min and Count Sketch, HyperLogLog distinct counting and mergeability for distributed systems.Advanced110 min
  25. 25Online algorithms and competitive analysisMany decisions are made without knowing the future: cache eviction, when to buy rather than rent, or which server receives a request. Competitive analysis compares against an optimum that knows the future. Study deterministic and randomized ski rental, LRU paging and its k bound, randomized marking and H_k, Yao's minimax principle and an O(1) LRU cache.Advanced95 min
  26. 26Parallel algorithms: work, span and scanUse the machine-independent work–span model for parallel algorithms: work is sequential cost and span the task DAG's critical path. Prove Brent's theorem, design parallel reduction and Blelloch scan, apply scan to associative operators such as affine recurrences behind state-space models, and study sorting networks, pointer jumping and work-stealing scheduling. GPUAdvanced115 min
  27. 27P, NP and the Cook-Levin theoremNP-completeness theory explains why thousands of important problems resist efficient solution. Define decision, search and optimization problems, P and NP through verifiers, polynomial reductions and NP-completeness. Prove Cook–Levin by encoding a Turing machine execution as a formula, and study coNP and the self-reducibility converting decision into search.Core115 min
  28. 28The art of reductions: a catalogue of NP-complete problemsProving NP-completeness is a design skill: choose a source problem and build gadgets. Follow Karp's reduction tree from 3-SAT to independent set, clique and vertex cover, 3-coloring, Hamiltonian cycle and traveling salesperson, subset sum and partition. Distinguish weak from strong NP-hardness and extract reduction design patterns for new problems.Core120 min
  29. 29Beyond NP: space, hierarchies, randomness and countingThe complexity landscape is much richer than P and NP. Prove hierarchy theorems by diagonalization, study space complexity (L, NL, PSPACE) and Savitch's theorem, PSPACE-completeness of TQBF and generalized games, the polynomial hierarchy, randomized classes BPP, RP and ZPP, the counting class #P and the permanent, and circuit complexity.Advanced110 min
  30. 30Coping with NP-hardness: exact, parameterized and fine-grained algorithmsNP-hardness does not end the conversation. Study exact algorithms improving on brute force, including branch and bound and meet-in-the-middle; parameterized complexity through bounded search trees, kernelization and FPT; ETH and SETH; and fine-grained complexity, which explains why polynomial-time problems such as edit distance and all-pairs shortest paths resist substantial improvement. GPUAdvanced115 min
  31. 31Approximation algorithms: greedy and LP roundingWhen the optimum cannot be obtained, proximity can be guaranteed. Define approximation ratios and learn to bound the unknown optimum. Study 2-approximations for vertex cover via matching and linear relaxation rounding, greedy set cover with factor H_n and randomized rounding, metric traveling salesperson with doubled spanning tree and Christofides, k-center, and Graham's parallel machine scheduling.Core115 min
  32. 32Approximation schemes, primal-dual method and hardness of approximationSome problems can be approximated arbitrarily closely while others cannot pass a threshold. Construct the knapsack FPTAS by scaling and rounding, study primal-dual methods and guaranteed local search, and examine the other side: the PCP theorem, gap reductions, Håstad and Feige's optimal thresholds, the unique games conjecture and semidefinite programs.Advanced115 min
  33. 33Frontier: beyond worst-case analysis and AI-discovered algorithmsCurrent algorithm research crosses machine learning in both directions. Study beyond-worst-case analysis (smoothed analysis and universal optimality), prediction-augmented algorithms combining consistency and robustness, learned indexes, nearly linear-time maximum flow, neural algorithmic reasoning, and algorithms discovered by search guided by networks and language models: AlphaTensor, AlphaDev, FunSearch and AlphaEvolve. GPUResearch110 min

Module capstone

Code graph analysis engine: reachability, cuts, signatures and optimization with guarantees

Build an engine on a real call or dependency graph extracted from a large open-source project, such as the PyPI dependency graph or a call graph generated by a static-analysis tool. Integrate the full module: (1) CSR representation, strongly connected components, condensation and topological ordering; (2) reachability and weighted shortest paths from untrusted inputs to sensitive functions; (3) a minimum vertex cut separating sources from sinks via maximum flow, giving a minimum set of sanitization points; (4) source-code signature scanning using an Aho-Corasick implementation of your own and duplicate-fragment detection with a suffix array and LCP; (5) streaming statistics using HyperLogLog and count-min; (6) minimum test selection to cover every reachable function, formulated as set cover and solved using the H(n)-approximate greedy algorithm, LP rounding and an exact OR-Tools solver to measure the actual gap. Deliver a library with property tests against networkx and SciPy, an empirical scaling report with log-log plots and estimated exponents, and an analysis of which parts are polynomial, which are NP-hard and what guarantee each approximation provides.

Check what you already know

  • Distinguish polynomial from pseudopolynomial cost in terms of the size of the input encoding.
  • Write binary searches without boundary errors using a half-open interval invariant.
  • Solve divide-and-conquer recurrences with the master theorem and justify the case used.
  • Calculate the expected number of comparisons in randomized quicksort using indicator variables.
  • Choose a potential function and prove the amortized cost of a dynamic array with shrinking.
  • Prove that building a binary heap takes O(n) time and implement decrease-key using a position index.
  • Analyze the expected cost of a hash table using universal hashing and explain hash flooding.
  • Restore red-black tree invariants after an insertion using rotations and recoloring.
  • Apply the access lemma to bound the amortized cost of a splay operation.
  • Design a segment tree with lazy propagation for a given associative operation.
  • Implement union-find with path compression and union by rank and explain the inverse Ackermann bound.
  • Construct the Aho-Corasick automaton and the KMP prefix function.
  • Construct a suffix array and its LCP array and count occurrences with the FM-index.
  • Prove the optimality of a greedy algorithm using an exchange argument or matroids.
  • Formulate the subproblem graph for a dynamic program and reconstruct its optimal solution.
  • Solve dynamic programming problems on intervals, trees and subsets.
  • Accelerate dynamic programming with the convex hull trick, divide-and-conquer optimization or Knuth optimization.
  • Compute strongly connected components using Tarjan's algorithm and find a topological order.
  • Choose among Dijkstra, Bellman-Ford, DAG shortest paths and Floyd-Warshall and prove Dijkstra's correctness.
  • Prove the cut property and compare Kruskal, Prim and Borůvka.
  • Compute a maximum flow using Dinic's algorithm and extract a minimum cut from the residual graph.
  • Solve the assignment problem using the Hungarian algorithm or minimum-cost flow.
  • Analyze Karger's algorithm and amplify the success probability of a Monte Carlo algorithm.
  • Size a Bloom filter and a count-min sketch for a given error rate.
  • Calculate the competitive ratio of LRU and ski rental.
  • Analyze the work and depth of a parallel scan and apply Brent's theorem.
  • Prove that a problem belongs to NP using a verifier and state the Cook-Levin theorem.
  • Construct a polynomial reduction from 3-SAT to a graph problem and prove its correctness.
  • Classify a problem in PSPACE, #P or BPP and justify the classification.
  • Design a kernel for parameterized vertex cover and explain a fine-grained reduction under SETH.
  • Design a 2-approximation using LP rounding and analyze greedy set cover.
  • Construct an FPTAS for knapsack and explain the PCP theorem.

References

  • Introduction to AlgorithmsThomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein, 2022
  • Algorithm DesignJon Kleinberg, Éva Tardos, 2005
  • AlgorithmsJeff Erickson, 2019
  • AlgorithmsRobert Sedgewick, Kevin Wayne, 2011
  • Computational Complexity: A Modern ApproachSanjeev Arora, Boaz Barak, 2009
  • Introduction to the Theory of ComputationMichael Sipser, 2012
  • Probability and Computing: Randomization and Probabilistic Techniques in Algorithms and Data AnalysisMichael Mitzenmacher, Eli Upfal, 2017
  • Randomized AlgorithmsRajeev Motwani, Prabhakar Raghavan, 1995
  • The Design of Approximation AlgorithmsDavid P. Williamson, David B. Shmoys, 2011
  • Computers and Intractability: A Guide to the Theory of NP-CompletenessMichael R. Garey, David S. Johnson, 1979
  • The Art of Computer Programming, Volume 3: Sorting and SearchingDonald E. Knuth, 1998
  • Beyond the Worst-Case Analysis of AlgorithmsTim Roughgarden (ed.), 2021