Algorithms in Practice
When two algorithms have the same big-O, what decides which one is fast?
The part opens with two loops that add up n numbers, one over an array and one along a shuffled linked list: the same linear bound, and very different measured times. Its first half builds the everyday tools: prefix sums and difference arrays, Fenwick trees from the lowest set bit, segment trees over any associative operation, sparse tables and lowest common ancestors, two pointers and monotonic stacks, binary search on a monotone predicate, word-level bit tricks, meet in the middle and square-root blocks. Its second half is algorithm engineering on the rendering machine: search layouts from a sorted array to Eytzinger order and a 16-key node compared by vector instructions, a vectorized tokenizer, a Swiss-style hash table, radix sort against comparison sort, and the top twenty by a heap. A chapter on benchmarking says what such timings can and cannot show, and the part keeps to it: no cache-miss counter was collected, so no cause is claimed. The Job is engineered natively for the ledger's tenth row, the first measured on real hardware rather than modelled. The part ends with learned indexes and algorithms that use predictions.
What you need. Two's complement and bitwise operators; enough C to read a short loop.
- Mathematics, ideas and history
- prefix sums, Fenwick and segment trees, RMQ and LCA, two pointers and monotonic stacks, bit tricks and the Four Russians, algorithm engineering, honest benchmarking
- What we build or compute
- the Job engineered (SIMD, Swiss table)
What you will be able to do
Degree
- Answer range-sum queries with prefix sums and apply range updates with a difference array.
- Trace a Fenwick tree's query and update loops with the lowest-set-bit step, and say which cells each one touches.
- Solve a problem with two pointers or a monotonic stack and prove it linear by counting pushes and pops.
Graduate
- Build a segment tree for an associative operation with a small record per node, such as the four numbers of the maximum subarray, and add lazy range updates.
- Explain why a sparse table answers range minima in constant time but not range sums, and reduce range minimum to lowest common ancestor and back.
- Count the 3^n iterations of submask enumeration, and use meet in the middle to halve an exponent.
Research
- State what a learned index certifies about a lookup and what its model can cost in the worst case.
- State the consistency and robustness bounds of ski rental with a prediction, and propose a cost model that could be tested on held-out workloads.
Industry
- Choose a search layout, a hash table or a sort for a hot path from measurements, and say which mechanism the measurement does not isolate.
- Design a benchmark with a fixed sample plan, interleaved variants, an observable result and an output check, and report its spread.
- Use Amdahl's law with a measured phase fraction to predict what speeding up one phase can give.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 17 min · Graduate 37 min · Research 41 min · Industry 28 min.
- 0Same big-O, different worldsDegree1 min
- 1Prefix sumsDegree3 min
- 2Fenwick treesDegree3 min
- 3Segment treesGraduate3 min
- 4Range minimum and lowest common ancestorsGraduate3 min
- 5Two pointers and monotonic stacksDegree2 min
- 6Searching for the answerDegree3 min
- 7Bits and the Four RussiansGraduate2 min
- 8Meet in the middle and square rootsGraduate2 min
- 9Algorithm engineering I: layoutsIndustry2 min
- 10Algorithm engineering II: SIMD and hashingIndustry2 min
- 11Sorting in practiceIndustry2 min
- 12Benchmarking honestlyIndustry2 min
- 13Problem solving as a craftDegree2 min
- 14The Job, engineeredIndustry2 min
- 15Frontier: learned indexes and predictionsResearch4 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.
Same big-O, different worldsDegree1 min
Here are two loops that add up n numbers. The first walks an array in order. The second follows a linked list with nodes shuffled through an allocated pool. Both compute the same sum in linear time. That asymptotic classification leaves constants and the memory-access pattern unspecified. Contiguous accesses can benefit from cache lines and prefetching, while following pointers creates dependencies between addresses. Those mechanisms motivate the experiment; elapsed time alone does not measure cache misses or identify their individual contributions.
Here they are, timed on this shared machine. The first marked point is a thousand elements. Read its measured ratio beside the plot. The second is sixty-five thousand elements. The last is sixteen million. All five native trials, the compiler flags and the complete sum checks are retained. The plotted minima describe this workload on this host, and can change on another run. Big O still describes growth; the measurements add information about these implementations. This part builds everyday algorithmic tools, then asks what their concrete costs are.
1Prefix sumsDegree3 min
The simplest precomputation in the business. Here are sixteen numbers, and we will be asked, over and over, for the sum of some stretch of them. Walk the array once and write down the running totals: S of i is the sum of everything before position i. Now any range sum is one subtraction. Positions three to ten: the total up to eleven, minus the total up to three, forty-four minus eight, thirty-six. Linear work once, then constant work per question. Nearly every index in this part makes some version of that trade.
Run the idea backwards and it handles updates. Suppose we must add three to positions two to nine, two to positions five to twelve, and one to positions zero to four. Doing it directly touches every position in every range. Instead keep a difference array: for each update, add the amount where its range starts and subtract it just after the range ends. Two cells per update, however long the range. One prefix sum at the end rebuilds the array: the running total switches each update on at its start and off after its end. In two dimensions the same trick costs four corners per rectangle.
Prefix sums work in two dimensions. Here is a small image. Its integral image stores, at each position, the sum of every pixel above and to the left. One pass builds it. Then the sum over any rectangle is four lookups: the corner below and to the right, minus the two strips we do not want, plus the corner we subtracted twice. Paul Viola and Michael Jones built real-time face detection on this in 2001: thousands of rectangle features per window, each in constant time, as the AI series showed. Frank Crow had used the same tables in 1984 to blur textures in computer graphics.
One more property makes prefix sums a workhorse: they parallelize, although each total seems to depend on the one before. In the first round, every element adds its left neighbour. In the second, every element adds the value two places to its left; in the third, four places. After log n rounds every position holds its prefix sum, and each round is done by all elements at once. Daniel Hillis and Guy Steele ran this on the Connection Machine, and Guy Blelloch made it work-efficient. Graphics cards use scans to compact streams, to sort, and to handle sparse matrices.
2Fenwick treesDegree3 min
Prefix sums answer in constant time, but one update can force n of them to change. Peter Fenwick's tree of 1994 balances the two, with one array and two loops. Cell i stores the sum of a range ending at i whose length is the lowest set bit of i. Odd cells hold one element; cells that are multiples of two but not four hold two; multiples of four, four; and so on. The lowest set bit is i and minus i, in two's complement, the trick from Part 4. To sum the first thirteen elements, take cell thirteen, then strip its lowest bit to get twelve, then eight, and stop at zero. Three cells cover one to thirteen exactly. To add to element five, update every cell whose range contains five: add the lowest bit instead. Five, six, eight, sixteen.
Why is it right, and why fast? A query clears one set bit of its positive index each step. Its responsibility intervals partition the requested prefix. The exact count is the index's population count, bounded by floor log base two of n plus one. An update moves its lowest set bit left until the index exceeds n, with the same logarithmic bound. Zero is a valid empty-prefix endpoint but never a valid update index. These are two traversals of the same interval representation. The table measures a fixed seeded mixture of updates and queries, with every final cell independently checked. Its average is an observation of that distribution, rather than a universal half-logarithm identity.
How do they compare on a real machine? All four structures hold two to the twenty values, but their timed operation counts differ. The slow plain and prefix arrays receive only the first thousand and twenty-four operations; Fenwick and segment trees receive the full million-operation trace. The caption makes this distinction explicit. Read the per-operation minima from three process runs. Complete answer streams are checked against an independent block-sum reference after timing. This demonstrates the cost of linear updates or queries at this scale. It is not an equal-length, steady-state benchmark of all four structures. Fenwick's original application was arithmetic coding's frequency tables, a useful example of matching operations to a data structure.
3Segment treesGraduate3 min
Fenwick trees need an operation you can undo, like subtraction. For the minimum of a range you cannot subtract, and you need a segment tree. Build a balanced tree over the array. Each node holds the minimum of the stretch below it: the leaves are the elements, the root the whole array. Any associative operation works the same way. To answer positions three to twelve, descend from the root and stop at every node whose range lies entirely inside the query. Four nodes cover this range. At most two per level ever do, so a query costs logarithmic time. Changing one element changes only the nodes above it, one per level. Minimum, maximum, greatest common divisor, matrix products: anything associative. Even the maximum subarray sum, if each node keeps four numbers instead of one.
The trick that makes segment trees so flexible is that a node can carry a small record instead of one number. Take the maximum-sum stretch of consecutive elements, the problem Bentley made famous. For each half, keep four numbers: its total, its best prefix, its best suffix, and its best stretch anywhere. Two halves combine in constant time. The total adds. The best prefix is either the left's, or the whole left plus the right's best prefix, and the suffix is the mirror image. And the best stretch lies in the left half, in the right half, or across the middle, where it is the left's best suffix joined to the right's best prefix. Here the winner is the one that crosses: six, which brute force confirms. Because this combination is associative, the segment tree can answer the maximum subarray of any range, while elements change underneath it.
What if updates cover ranges too? At each fully covered segment, change its sum by the update times segment length and leave a pending tag. Push that tag before a later operation descends below the node. This maintains both stored sums and deferred effects. The seeded experiment counts nodes visited by five hundred updates; an independent difference-array construction checks every final element after the count is captured. Persistence is a related, separate construction. A point update copies its logarithmic root-to-leaf path. A persistent lazy range-update tree also needs a consistent policy for copying tags and children; that extension is discussed rather than implemented here.
4Range minimum and lowest common ancestorsGraduate3 min
If the array never changes, a range minimum can be answered with two table lookups. Precompute the minimum of every window whose length is a power of two. Row zero is the array itself; each row is built from the one above, the smaller of two neighbouring windows. That is n log n numbers. To answer positions two to twelve, a range of eleven, take the largest power of two that fits, eight, and look up two windows of length eight: one starting at the left end, one ending at the right end. They overlap, and for the minimum that does not matter, because the minimum of a number with itself is that number. For a sum the overlap would be counted twice, which is why sums use the trees of the last two chapters.
In a rooted tree, the lowest common ancestor is the deepest node above both query nodes. An Euler tour records nodes and depths on entry and after returning from each child. Between the first occurrences of seven and four, the minimum depth identifies their ancestor, node one. Our implementation uses a sparse table, with n log n preprocessing and constant-time queries. The linear-preprocessing theorem cited later uses a different construction. Binary lifting instead stores ancestors at powers of two and answers in logarithmic time. These statements concern a rooted tree. A version-control history is generally a directed acyclic graph and can have several merge bases; it requires the broader treatment in Part 41.
The reduction runs the other way as well. Recursively put an interval's leftmost minimum at its Cartesian-tree root. Equal values are ordered by their array indices, so parent values need only be no larger than child values. A monotone stack builds this tree in linear time. The lowest common ancestor of two array positions is their interval's leftmost minimum. Our checks cover every illustrated range and node pair. Bender and Farach-Colton give a linear-preprocessing, constant-query construction. Succinct results can encode the static query structure in two n plus lower-order bits; this is an index-space theorem, not the memory use of our Python sparse table.
5Two pointers and monotonic stacksDegree2 min
Slide a window of four along an array and report each maximum. Checking every element separately costs n times k. Maintain a deque of indices with strictly decreasing values. When a new value arrives, remove smaller or equal values from the back: the newer equal value expires later. The diagram displays their values for readability. Remove an expired index from the front; the surviving front supplies the maximum. Each index enters once and leaves at most once, which proves linear total work. This amortized argument counts all iterations of the inner loop across the complete input. It does not assume the deque has constant length.
The window need not have a fixed width. Find the longest substring without repeated letters. Move the right end forward; if its new letter is already present, move the left end just beyond the previous occurrence, never backwards. A last-position table makes the illustrated fixed-alphabet updates constant time. Both endpoints advance at most n times, giving linear total work. Similar windows solve other problems only when their feasibility has the required monotonicity. In particular, the usual budget-sum window requires nonnegative values. Negative values can make extending a window decrease its sum, invalidating that simple rule.
A stack can be monotone too. To find each next strictly greater value, keep indices awaiting an answer and pop those with smaller values when a new element arrives. Equal values may remain. Each index is pushed and popped at most once, proving linear total work. The histogram routine uses a different, explicit tie rule: it also pops equal heights. A pop identifies a candidate span, but an equal-height pop need not find a strictly lower right boundary. The later representative can extend the same-height rectangle. Enumerating every possible rectangle independently confirms the illustrated maximum area, sixteen. The reusable idea is a monotone frontier plus a precise invariant; equality rules depend on the question being answered.
6Searching for the answerDegree3 min
Binary search works on a monotone predicate, not just a sorted array. These nonnegative package weights must be shipped in order within four days. A greedy feasibility check fills each day until the next package would exceed capacity. Larger capacities remain feasible. Search between the largest weight and the total weight. The routine first checks that the upper bound is feasible, and counts that actual predicate call along with the search calls. The minimum capacity is eighteen. State the monotonicity and feasible-endpoint contract before applying this pattern to other problems. The displayed lower-bound implementation has a separate half-open interval invariant. Tests cover empty arrays and boundary answers; finite tests support the implementation while the invariant explains its correctness.
Binary search is famous for being easy to get wrong, so here is a version to trust. Keep an invariant: everything to the left of lo is smaller than x, and everything from hi onwards is at least x. Each step shrinks the gap between them, and when it closes, lo is the answer. Use half-open ranges, from lo up to but not including hi, and the plus-or-minus-one guesswork disappears: the empty range is simply lo equal to hi. Compute the middle as lo plus half the difference. Adding lo and hi first overflows a 32-bit integer once an array has a billion elements, a bug Joshua Bloch found in 2006 in Java's own library, where it had sat for nine years. And return the boundary, the first position not less than x, rather than just found or not found. Lower and upper bounds answer counting and range questions too.
Sometimes you know roughly where the answer is. Galloping probes exponentially increasing distances, then binary-searches the bracket. This routine searches a sorted suffix starting at the supplied index. To obtain the global lower bound, all preceding elements must be smaller than the target. Work is logarithmic in the distance plus one. The table counts actual key reads for both methods, including bound construction, instead of substituting a logarithmic estimate. Close answers can need fewer reads; the crossover depends on the exact search loops and target. Merging sorted runs and intersecting posting lists often provide a useful starting position. Ternary search is a separate pattern for a unimodal objective on a valid finite interval; an arbitrary function need not satisfy that premise.
7Bits and the Four RussiansGraduate2 min
A sixty-four-bit machine word can represent a set of sixty-four positions. Population count may use a hardware instruction when the target ISA supports it. Clearing the lowest set bit visits the members one at a time. Isolating that bit gives the Fenwick step. Exclusive-or with a one-bit right shift gives a Gray-code sequence, whose neighbours differ in one bit. Fixed-width set union and intersection use a bounded number of word operations. A Python integer can span many machine words, so its bit-operation cost grows with its stored length. Negative patterns are excluded from these finite-subset routines. Warren's Hacker's Delight collects such transformations; check width, signedness and instruction support before translating one to native code.
Some dynamic programs run over every subset of a set, and need every subset of each subset. These three lines visit every submask of m, from m itself down to zero: subtract one, which borrows through the lowest member, and mask, which throws away what is not in m. Over all masks of n elements the loop body runs three to the n times, not four to the n, because each element is either outside the mask, in the mask but not the submask, or in both. We counted: exactly three to the n, every time. That is the inner loop of dynamic programming over subsets, for partitions, schedules and Steiner trees.
Word packing is related to the Four Russians tradition, but the mechanisms should be distinguished. The historical method groups small subproblems and precomputes their possible answers. Our experiments below use direct word-parallel operations rather than implementing that complete table-based algorithm. Packed transitive closure processes sixty-four columns per stored word. Every reachability result is checked against independent breadth-first searches. The LCS experiment compares full dynamic programming with a multiword bit algorithm on the same generated strings. Carry propagation spans all words of a row; the measured ratios are in the table. Both programs run three times and retain their raw clocks. Packing can improve constants and word-operation counts, while storage, preprocessing and multiword work remain part of the cost model.
8Meet in the middle and square rootsGraduate2 min
Meet in the middle reduces the exponent of some exhaustive searches. Subset sum asks whether selected numbers total a target. The brute-force routine here enumerates all subsets. Generate the sums of each half, sort one list, then search it for the complement of each sum in the other. The sorting and searches contribute additional factors; the displayed work counter counts generated sums and search calls, not every comparison or bit operation. The twenty-item example agrees with brute force; both have three retained timing trials. At forty items, two million generated sums replace a trillion full subsets, but sorting, exponential storage and the bit lengths of sums still matter. Bidirectional search uses a related meet-in-the-middle idea, with its own graph and stopping conditions.
Square-root decomposition divides work another way. Store totals for blocks of about square root n elements. A query scans boundary fragments and uses whole-block totals in the middle; the displayed example counts every touched element or block. Its update and query costs depend on the stored summary; not every operation admits an equally cheap merge. Mo's algorithm instead reorders offline queries by endpoint blocks and maintains a moving answer. It needs efficient add and remove operations for that statistic. For all twenty thousand distinct-count queries, we retain the deterministic input specification and output hash, and check every answer with an independent last-occurrence sweep using a sum tree. Pointer moves are an abstract work count, separate from Python wall time.
9Algorithm engineering I: layoutsIndustry2 min
Search layout changes the concrete implementation of a lower-bound query. In a sorted array, binary search visits progressively smaller intervals, often at distant addresses. Eytzinger order stores an implicit tree breadth first, with children at twice the parent index and twice plus one. This groups top levels and can make a future region suitable for explicit prefetching. Our code bounds the prefetch address within the allocation. The array B-tree packs sixteen thirty-two-bit keys into a sixty-four-byte node and uses an AVX-512 vector comparison, followed by a mask count and child selection. Khuong and Morin study these layouts. Our experiment measures the exact retained implementations on this host; it does not measure a cache-miss rate or prove which microarchitectural mechanism caused a speed difference.
Each size receives a million generated lookup queries. The red curve is ordinary binary search, with minima from three repetitions. Full sources, ISA flags and raw clock reads accompany the data. Branch-free binary search changes the instruction sequence. Its relative performance is specific to this processor and workload. Eytzinger order adds a different layout and explicit prefetching. The array B-tree uses sixteen-way AVX-512 comparisons within a node. Every actual answer is checked after timing against a certified lower-bound value. These implementations perform different scalar and SIMD work. Their elapsed times alone do not isolate cache misses, branch misses or prefetch effects. They share a lookup specification, rather than an identical comparison trace.
Branches are another possible cost. This experiment stores values from zero to two hundred and fifty-five in thirty-two-bit integers, then sums those at least a hundred and twenty-eight. We compare shuffled and sorted order using the same multiset. The branchy function disables if-conversion and vectorization. A separate histogram certifies the sum. The observed timing difference is consistent with a branch-prediction explanation, but no branch-miss counter was collected. A mask-based function provides another implementation on the same inputs. Read all four measured times. Their ordering describes these loops; it does not establish that predictable branches are universally free or that binary search is always limited by memory.
10Algorithm engineering II: SIMD and hashingIndustry2 min
The isolated tokenizer finds ASCII words and lower-cases letters. On this AVX2-capable host it loads thirty-two bytes, combines case bits, subtracts the code for a, and compares the lanes. Several vector instructions implement that sequence. Movemask gathers the lane results into an integer mask. A word begins where a letter has a non-letter predecessor; the mask carries boundary state between vector blocks. The table reports scalar and vector timings on the complete corpus. After each trial, we check every transformed byte and every word-start mask, as well as total words and letters. The simdjson work illustrates related classification techniques.
Compilers can vectorize some loops automatically. We compile the same three kernels at O one and at O three with the native ISA enabled. The table gives measured costs per element, amortized over fixed loop counts; the disassembly is retained. Restrict promises the relevant pointer regions do not overlap. It is a contract the caller must obey, rather than a request that makes arbitrary aliasing safe. The prefix kernel carries a dependency; an ordinary scalar loop is not the parallel scan shown earlier. Every final array element and reduction is checked outside the timers. These builds change several optimizations together. Inspect the actual assembly to identify vector instructions, and avoid attributing the entire timing difference to vectorization alone.
Vector comparisons also help hash-table lookup. Our teaching Swiss-style table stores sixteen control bytes per group, each carrying an empty marker or seven hash bits. An SSE2 comparison filters candidate slots, followed by full key checks. Group probing and collisions still require work. The two open-addressing tables use the same requested capacity and occupancies. The standard unordered map chooses its own bucket count, which is recorded separately. Read insertion and lookup times for each workload. Every inserted-key count and every lookup is checked against an independently sorted multiset after timing. Production Abseil and other modern tables develop related ideas with additional policies and guarantees; this small implementation does not reproduce every production design.
11Sorting in practiceIndustry2 min
What does this production sort do? This GCC libstdc++ implementation uses an introsort family: quicksort partitioning with a depth limit. A fallback prevents the quadratic worst case of unguarded quicksort. The C++ interface specifies complexity requirements without mandating one algorithm for all libraries. This implementation finishes small partitions with insertion sorting. The cutoff is an implementation detail. Pattern-defeating quicksort is another important family, rather than a timeless description of every language's current library. Timsort and related run-merging policies exploit existing order. Python and Java have type- and version-specific choices; primitive arrays need not use the object-sorting algorithm. Match any library claim to a concrete version, type, comparator contract and retained build.
Comparison sorting has an n log n worst-case lower bound for arbitrary distinct keys. Our radix sort instead uses thirty-two-bit unsigned keys and four stable byte passes, including a fixed counter-array cost per pass. Small batches can be dominated by that overhead. The crossover in this measurement is a finite workload result, not a universal threshold. Each timed batch includes its input copy; every output element of every batch is retained until checked against the library sort after the timer. Three repetitions supply the plotted minima. The word-RAM explanation assumes bounded-width keys. Wider integers, memory traffic, temporary storage and parallel implementations change the comparison.
Often the complete order is unnecessary. Here four methods extract the twenty largest of sixteen million generated keys. Full sort, partial sort and a small heap solve different amounts of ordering work. An independent fixed-size sorted insertion reference checks every returned top-twenty list. The standard nth-element contract gives linear average complexity for this nonparallel overload, rather than a universal worst-case linear promise. Its timing includes sorting and extracting the selected twenty. Array input copies are outside these timers; heap construction and extraction are inside its timer. The measured winner belongs to this fixed k and distribution. Choosing the required output specification can matter more than tuning a full sort.
12Benchmarking honestlyIndustry2 min
The benchmark demonstration records thirty process runs, with six observations in each. We retain every observation and compare the first with the median of the later five, so a single sample is not compared with a selected minimum. Any first-versus-later difference can have several causes. These clocks alone do not establish a cold-cache effect or a particular change in processor frequency. The plot uses an axis that contains all current observations. For a controlled comparison, choose a sample plan in advance, randomize or interleave variants, and report uncertainty and the sampling unit. Repeating until a preferred confidence interval appears requires a valid sequential procedure; ordinary fixed-sample intervals do not justify optional stopping.
Two traps illustrate why controls matter. We vary an environment variable's size with a fixed, shuffled execution schedule, retaining five process runs per size. The observed spread also includes shared-host variation and uncontrolled address randomization, so it does not isolate a causal layout effect. Mytkowicz and colleagues studied measurement bias from layout choices. Curtsinger and Berger's Stabilizer samples layouts during execution; our small demonstration does not reproduce that system. The second trap is dead-code elimination. The unused loop has no observable result; inspect the retained assembly alongside its clock interval. The kept version has an independently checked exact sum. Its measured time is shown rather than quoted from an earlier host. A benchmark needs both observable work and a correctness check.
13Problem solving as a craftDegree2 min
Pólya's problem-solving advice is useful for programs. Understand the specification and work small cases, including empty inputs and boundary values. Devise a plan by recognizing structure, then state the assumptions that make it applicable. Implement a simple independent reference before optimizing. Look back: explain an invariant and compare complete outputs on targeted and generated cases. Tests can expose counterexamples without proving every possible execution correct. This episode's receipts identify which illustrated algorithms, input domains and native workloads were actually checked.
Count unordered index pairs whose sum is at most T. With one, two, three and threshold four, the valid pairs are one with two, and one with three. The empty input has none. Sorting preserves the pair count. If the smallest remaining value plus the largest fits, that smallest value pairs with every remaining position between them. Count those pairs and advance the left pointer; otherwise decrease the right pointer. This remains valid for negative values and duplicates because the sorted-order inequalities still hold. Two thousand retained small fixtures agree with brute force. The timing table uses three fixed repetitions per method after input preparation, followed by equality checks; it does not replace the invariant proof.
Algorithmic fluency comes from recognizing recurring structures. The course's catalogue includes counting maps, windows, heaps, graph traversals, union-find, dynamic programming, tries and string matching. Some are implemented in earlier episodes; others are applications or design exercises. A catalogue is not a certificate that every possible variant has been built and tested. Practical judgment also asks for input limits, operation mix, memory use and an appropriate measurement plan. Skiena's Algorithm Design Manual organizes problems by related structures, a useful companion to Pólya's planning step.
14The Job, engineeredIndustry2 min
The Job counts the words of the fixed thirty-novel corpus and selects the twenty most common. The engineered version classifies ASCII bytes with AVX2. It hashes letter blocks while retaining exact key comparisons. A teaching Swiss-style table filters sixteen control bytes at once. The first eight letters, length and count live in the slot; longer words also consult their stored bytes. Its fixed table, pool and word-length bounds are checked against this corpus. Seven whole-program runs retain both minimum and median times, exact top-twenty output and every distinct word count, independently checked against Python. The comparison is empirical for these two programs on the same host. No hardware counters were collected, so we make no claim of one cache miss per word or a proven performance floor.
Amdahl's law is a model for a specified phase fraction. In this counterfactual example, suppose thirty percent of a program's baseline time belongs to a phase that can be accelerated. This fraction is an assumption, not a profile of our Job. Making that phase ten times faster gives a total cost of seventy plus three units, or speedup one over zero point seven three. Even an infinitely fast phase leaves seventy units. The isolated tokenizer timings cannot be subtracted from a different complete program to recover its phases. Measure phases in a consistent program and workload before using them for a prediction; evaluate the actual whole-program change separately.
The ledger now contains two kinds of quantity. Earlier Pebble rows are modeled costs under their stated machine and clock assumptions. The native row is measured wall time on the current host. Their numeric ratio is not an empirical speedup between two physical processors. Input conventions, implementations and modeled costs must be checked before making a cross-system claim. We do have a same-host comparison: Part 17's native C program and the engineered program process the same bytes with identical output and complete counts. Their seven observations are retained. Keep the modeled teaching ledger and the measured native experiment visibly distinguished; they answer different questions about the tower we built.
15Frontier: learned indexes and predictionsResearch4 min
A learned index predicts positions from keys. Our keys are the corpus's word-start byte offsets; their storage is reported separately. This teaching implementation greedily fits lines anchored at segment starts. It evaluates every stored-key error, then certifies each query's predicted search bracket and falls back to full binary search if needed. Every actual query is independently checked with NumPy searchsorted. Kraska and colleagues developed learned-index systems, while the PGM work provides stronger indexing constructions; our floating-point anchored fit is not its optimal segmentation algorithm. The table counts native segment structs and separator keys, including padding. It also records peak requested model storage. Lookup clocks exclude fitting and validation, and a smaller model can still incur segment-search and fallback costs.
Predictions can also guide an online decision. In discrete ski rental, buying costs B and each rental day costs one. If the forecast is at least B, buy at the start of day ceiling lambda B; otherwise use day ceiling B over lambda. Lambda lies above zero and at most one. The literature's one plus lambda consistency and one plus one over lambda robustness are upper bounds. Our table gives the tighter exact discrete worst case, attained at one of the two buy-day witnesses. With B ten and lambda one tenth, a short forecast and a hundred-day season cost a hundred and nine against optimum ten: ratio ten point nine. Synthetic Gaussian forecast experiments provide means, not worst-case proofs or trained-model performance. This deterministic policy illustrates the tradeoff studied by Purohit, Svitkina and Kumar. A forecast can help, while the guarantee must cover forecasts that are completely wrong.
Cost models describe selected resources. Our four searches share a lower-bound specification while performing different scalar comparisons, vector work and memory accesses. The word-RAM model counts bounded-width operations under its assumptions, not elapsed host nanoseconds. External-memory analysis instead counts transfers between memory levels with a specified block size and capacity. In an ideal-cache model, suitable cache-oblivious search layouts can achieve logarithmic-in-block-base transfer bounds without encoding the block size. Optimality requires the model's cache, block and problem assumptions; it is not a blanket statement about every real cache. Prefetching, SIMD, branches and shared-host interference call for additional modeling or controlled experiments. The research task is to specify a useful model and test its predictions on held-out workloads.
Here are three concrete research directions. Specify a cost model and evaluate whether it ranks unseen implementations and workloads. Dynamic learned indexes with worst-case guarantees already exist, including the PGM work. Reproduce an existing baseline before asking a narrower question about update patterns, adversarial keys or resource tradeoffs. For the segment experiment, separate a finite corpus fit from the probabilistic theorem. Under positive independent identically distributed gaps with finite nonzero variance, the paper analyzes a fixed-slope mean-exit-time construction in a suitable large-epsilon regime. Our anchored greedy fit is a different procedure. First reproduce that baseline on generated independent gaps. Then compare real, shuffled and correlated gaps across scales and seeds. A slope through a few corpus points is a descriptive statistic, not a new asymptotic law or a contradiction of the theorem.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Prefix sums, difference arrays and integral images; Fenwick and segment trees with explicit range contracts; static range minima and rooted-tree ancestors; monotone frontiers and answer search; word packing and exponential-search reductions. We then measured concrete native implementations with retained sources, raw trials and complete output checks. Their timings describe this workload and host. The Job's measured comparison and the modeled Pebble ledger remain separate kinds of evidence.
Where this comes back. Database indexes and query engines use tree layouts, bitmaps and vector batches. Version-control histories require ancestor reasoning on directed acyclic graphs. Search engines intersect posting lists and decode compressed values with SIMD. Systems work studies latency distributions under load, which calls for a sampling plan and controlled comparisons. The roofline model later relates arithmetic intensity to resource ceilings under stated assumptions. Together these topics show why choosing an operation count, memory model or empirical benchmark depends on the question.
In practice. Interviews test the patterns of chapter thirteen, with their costs and edge cases. Databases and search engines are built from B-plus trees, bitmaps, galloping intersections and vector scans. Games and exchanges keep leaderboards and order books in Fenwick and segment trees. And performance work on a hot path starts with a profiler and an honest benchmark, and usually ends with a better memory layout.
Six exercises have worked guidance in the notes. Pause to attempt one before reading its solution. The fifth asks for a bounded Fenwick design for Pebble: specify the vocabulary size, word-length limits and counter width before implementation. The notes include an independently checked arithmetic trace; they do not claim that a new Pebble port was executed. The last exercise is an experimental research plan. Reproduce the cited independent-gap baseline before interpreting a finite corpus slope, and record negative results as well as matches.
Next time, Act Five begins, with limits. Part 1 proved that one problem cannot be solved. Part 25 finds the same impossibility everywhere: in every non-trivial question about what programs do, in equations over the integers, in tilings of the plane, and in Gödel's theorem, all from the fact that a program can print its own source. And the busy beaver marks the place where proof itself runs out. Part 25, Undecidable.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. B+ trees and vectorized query execution return in Part 35; ancestor queries on a history that is a DAG, not a tree, in Part 41; columnar files and SIMD scans in Part 46; galloping intersection of posting lists in Part 47; tail latency against load in Part 48; the roofline model in Part 60. Act V begins with Part 25, Undecidable.
Key results
The part's results in one place, for revision.
Try it
Lab 24 · What a range structure touches
Drive a Fenwick tree, a segment tree and square-root blocks with the same random updates and range sums, check every answer against a plain array, and count the cells each one touches against popcount, 2 lg n and 3 sqrt(n); then check three linear-time or counting claims of the part by brute force.
python -m videos.cs.labs 24
needs numpy, scipy, matplotlib · download lab24.py ·
source on GitHubn = 16,384: cells per operation plain array 2,800.4 Fenwick tree 7.4 segment tree 31.9 sqrt blocks 84.7
bounds at that n lg n + 1 = 15 sqrt(n) = 128 mean range length about n / 3 = 5,461
sliding maximum, 20,000 values, window 50 19,998 deque removals (at most n; checking every window: 997,550)
submasks of all 9-bit masks 19,683 = 3^9 (not 4^9 = 262,144)
subset sum, 18 items meet in the middle 1,536 sums and searches, brute force 262,144 subsets
The counts follow the structure: a Fenwick query reads one cell per set bit of its index, a segment tree visits a few nodes per level, blocks cost a square root. They are counts of cells, not nanoseconds; the film's second half measures what the machine adds.
The code (94 lines; it asserts its own result)
"""Lab 24: count the cells that prefix sums, Fenwick trees, segment trees and square-root blocks touch."""
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 practice as pr
TITLE = "What a range structure touches"
GOAL = ("Drive a Fenwick tree, a segment tree and square-root blocks with the same random updates and range sums, "
"check every answer against a plain array, and count the cells each one touches against popcount, 2 lg n and "
"3 sqrt(n); then check three linear-time or counting claims of the part by brute force.")
TASKS = [
"Replace the segment tree's sum by min (op=min, ident=float('inf')) and check range minima against numpy. Why can the Fenwick tree not do the same?",
"Time the Fenwick loop against the plain array's a[l:r + 1].sum() at n = 2**16 with time.perf_counter. At which n does the count of cells stop predicting the time?",
"Change sliding_max's window from 50 to 5,000 and print the pops per element. Why does the amortized count not grow with the window?",
]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the same trace of updates and range sums on three structures, checked against a plain array
sizes = [2 ** k for k in range(4, 15, 2)]
per_op = {"plain array": [], "Fenwick tree": [], "segment tree": [], "sqrt blocks": []}
for n in sizes:
a = rng.integers(-50, 51, n).astype(np.int64)
fen, seg, blocks = pr.Fenwick(n), pr.SegTree(a.tolist()), pr.SqrtDecomp(a.tolist())
for i, v in enumerate(a.tolist()):
fen.add(i + 1, v)
fen.touched, ops, scanned = 0, 300, 0
for _ in range(ops):
i, v = int(rng.integers(n)), int(rng.integers(-50, 51))
a[i] += v
path = fen.add(i + 1, v)
seg.update(i, int(a[i]))
blocks.update(i, int(a[i]))
assert len(path) <= n.bit_length(), "an update climbs at most floor(lg n) + 1 cells"
lo, hi = sorted(int(x) for x in rng.integers(0, n, 2))
truth = int(a[lo:hi + 1].sum())
scanned += hi - lo + 1
cover = []
assert fen.range(lo + 1, hi + 1) == truth and seg.query(lo, hi, cover) == truth and blocks.query(lo, hi) == truth
assert len(cover) <= 2 * n.bit_length(), "at most two covering nodes per level"
fen.prefix(hi + 1)
assert len(fen.last_path) == pr.popcount(hi + 1), "a prefix query reads popcount(i) cells"
per_op["plain array"].append((scanned + ops) / (2 * ops))
per_op["Fenwick tree"].append(fen.touched / (4 * ops)) # one add and three prefix calls per round
per_op["segment tree"].append(seg.visits / (2 * ops))
per_op["sqrt blocks"].append((blocks.touched + ops) / (2 * ops))
assert blocks.touched / ops <= 3 * np.sqrt(n), "a block query touches at most about 3 sqrt(n) cells"
n = sizes[-1]
lab.row(f"n = {n:,}: cells per operation", " ".join(f"{k} {v[-1]:,.1f}" for k, v in per_op.items()))
lab.row("bounds at that n", f"lg n + 1 = {n.bit_length()} sqrt(n) = {int(np.sqrt(n))} mean range length about n / 3 = {n // 3:,}")
assert per_op["Fenwick tree"][-1] < per_op["segment tree"][-1] < per_op["sqrt blocks"][-1] < per_op["plain array"][-1] / 10
# 2. the sliding-window maximum: right, and linear
x = rng.integers(0, 1000, 20_000).tolist()
out, _, pops = pr.sliding_max(x, 50, trace=True)
assert out == np.lib.stride_tricks.sliding_window_view(np.array(x), 50).max(axis=1).tolist()
assert pops <= len(x), "each index leaves the deque at most once"
lab.row("sliding maximum, 20,000 values, window 50", f"{pops:,} deque removals (at most n; checking every window: {50 * (len(x) - 49):,})")
# 3. submasks: exactly 3^n loop iterations over all masks of n elements
total = sum(sum(1 for _ in pr.submasks(m)) for m in range(1 << 9))
assert total == 3 ** 9
lab.row("submasks of all 9-bit masks", f"{total:,} = 3^9 (not 4^9 = {4 ** 9:,})")
# 4. meet in the middle against brute force
items = [int(v) for v in rng.integers(1, 10 ** 6, 18)]
hit = sum(v for v, keep in zip(items, rng.random(18) < 0.5) if keep)
for target in (hit, hit + 1, sum(items) + 1):
(f1, w1), (f2, w2) = pr.subset_sum_mitm(items, target), pr.subset_sum_brute(items, target)
assert f1 == f2, "the same answer as trying every subset"
assert f1 is False and w1 <= 3 * 2 ** 9 and w2 == 2 ** 18
lab.row("subset sum, 18 items", f"meet in the middle {w1:,} sums and searches, brute force {w2:,} subsets")
lab.note = ("The counts follow the structure: a Fenwick query reads one cell per set bit of its index, a segment "
"tree visits a few nodes per level, blocks cost a square root. They are counts of cells, not nanoseconds; the "
"film's second half measures what the machine adds.")
fig, ax = labs.figure(2, size=(11, 4.4))
for (name, v), color in zip(per_op.items(), (labs.RED, labs.GREEN, labs.BLUE, labs.GOLD)):
ax[0].loglog(sizes, v, "o-", color=color, label=name)
ax[0].set(title="Cells touched per operation (updates and range sums)", xlabel="array length n", ylabel="cells")
ax[0].legend()
idx = np.arange(1, 65)
ax[1].bar(idx, [pr.popcount(int(i)) for i in idx], color=labs.GREEN, width=0.8, label="prefix query: popcount(i)")
ax[1].step(idx, [len(pr.Fenwick(64).add(int(i), 1)) for i in idx], where="mid", color=labs.GOLD, label="update: cells above i")
ax[1].axhline(7, color=labs.MUTED, ls="--", label="lg n + 1 = 7")
ax[1].set(title="A Fenwick tree on 64 cells: work at each index", xlabel="index i", ylabel="cells touched", ylim=(0, 9.5))
ax[1].legend(ncols=3, loc="upper center", fontsize=8)
lab.fig = fig
return lab
Now change it
- Replace the segment tree's sum by min (op=min, ident=float('inf')) and check range minima against numpy. Why can the Fenwick tree not do the same?
- Time the Fenwick loop against the plain array's a[l:r + 1].sum() at n = 2**16 with time.perf_counter. At which n does the count of cells stop predicting the time?
- Change sliding_max's window from 50 to 5,000 and print the pops per element. Why does the amortized count not grow with the window?
Problems, with solutions
Try each problem before opening its solution.
Six worked exercises / 六道习题解答
-
Fenwick partition and bound. Prove that a Fenwick prefix query visits at most \(\lfloor \log_2 n \rfloor + 1\) cells, and that its ranges tile \([1, i]\).
Solution
For positive
i, repeatedly removing its lowest set bit decomposes[1,i]into disjoint adjacent responsibility intervals. The query count is exactlypopcount(i), at mostfloor(log2(n))+1. Updating adds the lowest set bit, advancing its position until the index exceedsn, with the same logarithmic bound. 中文: 每次去掉最低置位比特,负责区间首尾相接,恰好划分前缀。 查询步数等于置位比特数;更新把最低置位比特向左推进,直到超过数组。 -
Deque amortization and ties. Prove that the sliding-window maximum's deque does at most \(2n\) pushes and pops in total.
Solution
Charge every push and removal to its index; an index enters once and leaves at most once, so total pushes plus pops are at most
2n. Removing equal tail values keeps the newer representative. The executed[2,2,1,3], width-two witness returns[2,2,3]. 中文: 每个索引最多入队、离队各一次,合计不超过二 n。 相等时保留较新的代表;执行见证的三个最大值为二、二、三。 -
Cartesian tree and RMQ. Show that every range-minimum query is a lowest-common-ancestor query in the Cartesian tree, and build the tree in \(O(n)\).
Solution
Recursively choose the leftmost minimum as root. In-order positions are array positions, so the LCA of two positions is their interval minimum. The monotone-stack construction pushes/pops each position at most once. For
[2,1,1,3], the executed parent array is[1,-1,1,2]. This implementation's sparse-table preprocessing isO(n log n); cited linear-preprocessing results use additional constructions. 中文: 递归选最左最小值,保持中序位置,因此区间最小值就是两端的祖先。 单调栈线性构造;当前稀疏表不是所引用的线性预处理结构。 -
All masks and submasks. Prove that enumerating every submask of every mask of \(n\) bits takes exactly \(3^n\) steps.
Solution
Each bit is absent, present only in the mask, or present in both: three independent choices give exactly
3^nbody visits, including zero submasks. The executed witness checksn=0..8. This counts visits; arbitrary-width arithmetic adds bit cost. 中文: 每位有不在掩码、只在掩码、同时在掩码与子掩码三种状态, 所以恰好三的 n 次方次访问;大整数的位代价另计。 -
Bounded Pebble design. Build. Specify a bounded Pebble Fenwick design: fixed vocabulary, word lengths, counter width. Check the notes' arithmetic trace before attempting a port.
Solution
First choose a fixed vocabulary and stable IDs. Store counts in a one-based Fenwick array; the top-
kfrequency prefix then answers the question only if IDs have been fixed in that frequency order. Vocabulary construction and re-ranking are separate problems. For a bounded eight-ID example, counts[3,1,4,1,5,9,2,6]giveprefix(5)=14; adding five at ID two touches[2,4,8]and changes it to19. The executed Python trace checks every final prefix. This unsorted-ID trace illustrates prefix arithmetic, not a top-k query. One concrete Pebble design can limit the vocabulary to eight ASCII words of at most sixteen bytes and use signed 32-bit counters. Reject an update if a word count would become negative or the total exceed2^31-1. A Pebble port must also bound pool storage, reserven+1counters, reject update index zero, and prove counters/totals fit the chosen signed width before incrementing. No new Pebble-language program or emulator execution is claimed by these notes. 中文: 先固定词表与稳定编号;只有编号已按频率固定排序,前 k 项和才回答 热门词计数。建词表与重排另算。八项见证中前五项为十四,编号二增加五, 访问二、四、八,答案变十九。这个未排序编号轨迹只演示前缀算术,不是前 k 查询。 一个具体设计可限定八个、每个至多十六字节的 ASCII 词,使用三十二位有符号计数; 若更新使计数为负或总和超过2^31-1,就拒绝。Python 轨迹核对全部前缀;移植还要证明 词长、字节池和有符号计数范围,并拒绝零更新位置。这里没有宣称执行新移植。 -
Reproduce a research baseline. \(\bigstar\) Research. Reproduce the IID fixed-slope mean-exit baseline; compare real and shuffled gaps across scales. A finite anchored-fit slope is not a new asymptotic law.
Solution
The cited mean-exit-time analysis assumes positive IID gaps, finite nonzero variance and an appropriate asymptotic regime.
worked_examples.pyexecutes 1,000 independent fixed-slope first-exit walks per epsilon on exponential gaps with population mean/variance one. For epsilon4,8,16,32, the seeded sample means are approximately21.96,74.12,281.96,1115.14; their ratios to epsilon squared are1.373,1.158,1.101,1.089. Raw lengths, pre-exit/exit errors, generator details and sample standard errors are retained. These finite observations illustrate overshoot/regime effects, not a theorem proof. Next reproduce several seeds and distributions, then compare real gaps, shuffled gaps and correlations with matching procedures. The corpus's anchored fit is a different algorithm; a slope through a few epsilon values is not a universal exponent or a contradiction of the IID result. Dynamic PGM already supports updates: reproduce that baseline before proposing a narrower question. 中文: 先复现正的独立同分布间隔上的固定斜率退出实验,再比较真实与打乱 间隔。保存长度、退出前后误差、种子和标准误。有限斜率不是渐近定律, 锚定贪心与论文构造不同;动态 PGM 已存在,新的问题需要更窄的范围。
Notes and sources
Sources
Primary references / 原始文献
Consulted 2026-11-11; these are cited results, not claims that every paper's system was implemented here.
- Khuong–Morin, array search layouts.
- Mytkowicz et al., measurement bias (2009).
- Curtsinger–Berger, Stabilizer (2013).
- Purohit–Svitkina–Kumar, predictions (2018), Algorithm 2.
- Ferragina–Vinciguerra, PGM (2020), including dynamic indexing.
- Ferragina–Lillo–Vinciguerra, learned-index effectiveness (2020).
The evidence packet binds the exact source and measurement snapshot. Sampled previews and automated speech checks are separate from continuous audiovisual listening, Chinese synthesized speech review, full native production review and production-pace runtime approval; those release gates remain open.
About this partfrom its README
This episode implements range structures, monotone frontiers, search, bit packing and decomposition, then measures specific native implementations. Complexity statements have explicit input and machine-model assumptions. Timings are finite observations on a shared host; they do not identify individual hardware causes.
本部分实现区间结构、单调边界、搜索、比特打包与分解,再测量具体原生实现。 复杂度结论需要明确的输入和机器模型前提。耗时属于共享主机上的有限观测, 不能单凭它分离硬件机制的因果贡献。
Run from the repository root:
What is computed and builtContracts and measurement scope / 约定与测量范围
- Ranges are inclusive in the practice instrument. Empty structures construct
safely; invalid indices/ranges fail before mutation. Fenwick updates require
indices
1..n; prefix queries accept0..n. Bit-subset routines require nonnegative integers. Histogram heights must be finite and nonnegative. - Cartesian minima use
(value,index)order, selecting the leftmost equal minimum. Sliding maxima discard older equal values. The histogram's equal-bar pop rule differs from next-strictly-greater queries. - Binary answer search requires a monotone predicate and checks a feasible upper endpoint. Galloping searches a sorted suffix; a global lower bound also requires all earlier elements below the target. Both search table columns count actual key reads, including bound construction.
- Native range benchmarks share
n=2^20, but naive arrays execute only the first2^10operations; trees execute2^20. Their per-operation figures therefore do not represent equal-length steady-state workloads. Every answer is checked against a separate square-root reference. - Every sort batch is checked, every map key count and lookup is checked, closure is checked by independent BFS, and native top-20 lists are checked by independent sorted insertion. Job checks all distinct counts, not just the displayed twenty. The fixed engineered Job has corpus-checked table/pool/word-length limits.
- Native Swiss-style code is a teaching implementation. Its requested occupancy
is separate from
unordered_map's actual bucket occupancy. ISA-dependent AVX2/AVX-512/SSE2 results apply to the retained host/build, not every CPU. - All 20,000 Mo answers are checked with an offline last-occurrence sum-tree reference. MITM's displayed counter counts generated sums and search calls; sorting, comparisons, bit costs and exponential storage remain additional costs.
- The learned index is an anchored greedy floating-point fit, not optimal PGM segmentation. Stored-key errors are evaluated; each query's bracket is certified with full-search fallback. NumPy independently checks every actual query. Active model bytes include native struct padding and separator keys. Peak requested storage is recorded separately, excluding key/query arrays and allocator overhead; it is not measured RSS. Lookup timers exclude fitting and validation.
- Ski rental uses discrete buy-at-start-of-day costs and exact rational ceilings. The exact worst ratio is witnessed at one of the two buy days, not estimated by a short season grid. Gaussian forecast means are synthetic observations.
- Amdahl's panel assumes a phase fraction. It is not a profile assembled by subtracting an isolated tokenizer from another program. The modeled Pebble ledger and native wall times are distinct quantities; their ratio is not a measured cross-processor speedup. Same-host native Job comparisons are separate.
区间为闭区间,空结构可构造,非法范围在修改前拒绝。Fenwick 更新从一开始, 空前缀允许零。相等值规则明确;预算和双指针要求非负值。二分答案先检查可行上界, 跳跃搜索明确后缀前提,比较表统计实际读取。四种区间基准的轨迹长度不同。 完整检查覆盖全部排序批次、映射答案、闭包、前二十、词频和 Mo 查询。 学习索引认证区间并回退,模型内存包含结构体填充与分隔键;租赁使用精确离散界。 Amdahl 占比是假设;Pebble 模型账本与原生墙钟时间分开解释。
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: an array and a shuffled linked list, both O(n), 5× apart at a thousand elements and 143× at sixteen million (measured).
- Prefix sums and difference arrays; the integral image (Crow 1984; Viola–Jones, AI, Built 6); the parallel scan (Hillis–Steele, Blelloch).
- Fenwick trees (1994): the lowbit trick i & −i; responsibility ranges drawn; both loops proved logarithmic; four structures timed (52 ns against 142 for a segment tree and 130–155 µs for the naive ones).
- Segment trees: covering nodes; a four-number node for the maximum subarray; lazy propagation (57 nodes against 17,552 elements); persistence.
- Range minimum and LCA: the sparse table (idempotence); LCA by Euler tour and by binary lifting; the Cartesian tree (Bender & Farach-Colton 2000; Fischer & Heun).
- Two pointers: the sliding-window maximum's deque; the longest stretch without a repeat; monotonic stacks (next greater element, the largest rectangle in a histogram).
- Searching: binary search on the answer; a binary search to trust (invariants, half-open ranges, Bloch's overflow); galloping (Bentley & Yao 1976); ternary search.
- Bits: popcount, the lowest set bit, Gray codes; submask enumeration (exactly 3ⁿ); the Four Russians in C, bitset closure (10×) and bit-parallel LCS (103×).
- Meet in the middle (Horowitz & Sahni 1974); square-root decomposition; Mo's order.
- Algorithm engineering I, layouts: sorted, branch-free, Eytzinger with prefetch and a 16-key B-tree layout with AVX-512 (Khuong & Morin 2017), 1 K to 64 M keys (908 against 184 ns); branch prediction measured (5.3 against 0.9 ns per element).
- Algorithm engineering II: an AVX2 word scan (8.8×); auto-vectorization; Swiss-style tables against linear probing
and
std::unordered_map(66, 171 and 82 ns at 7/8 full). - Sorting in practice: introsort, pdqsort and Timsort; the radix crossover at about 64 keys and 3.5× at 16 M; the top 20 of 16 M (a heap, 94× faster than sorting).
- Benchmarking honestly: warm-up and spread over thirty runs; environment size (Mytkowicz et al. 2009; Stabilizer); dead-code elimination.
- Problem solving as a craft: Pólya's four steps on a worked problem with a stress test; the interview repertoire mapped to the series' parts.
- The Job, engineered: an AVX2 tokenizer, word-at-a-time hashing and a Swiss-style table with inline keys, natively, against Part 17's C (155 against 75 ms); Amdahl's law; ledger row 10, the first measured on real hardware.
- Frontier: a learned index over the corpus's word offsets (PGM-style; 64 segments, 1.5× faster than binary search); ski rental with predictions (consistency and robustness); the theory–practice gap (external memory, cache-oblivious); open problems. Outro.
Computed: every number above, in videos/cs/cs24/compute.py with explainer/cs/algo/practice.py (tested in
tests/test_cs24_practice.py against brute force): the structures' operation counts; and native C and C++
benchmarks, each checked against a reference before it is timed: array against list, four range structures,
search layouts, branches, SIMD word finding, vectorization, three hash tables, radix against comparison sort, top-k,
benchmark spread and layout bias, dead code, the Job engineered, a learned index. Ski rental with predictions in
Python.
Visuals: Fenwick responsibility ranges as bars by lowbit; a segment tree lighting its covering nodes; the sparse
table's windows; an Euler tour; a Cartesian tree; a sliding window with its deque; a histogram's best rectangle; a
sorted array against its Eytzinger layout; a word's letters as a bitmask; a Swiss-table group; benchmark
distributions as strips of dots; Amdahl's bars; the ledger's tenth row.
In practice: the data structures inside databases, search engines, game engines and trading systems; the core
repertoire of coding interviews; performance work on hot paths.
Reading: Skiena, The Algorithm Design Manual; Bentley, Programming Pearls; Warren, Hacker's Delight;
Laaksonen, Guide to Competitive Programming; Halim & Halim, Competitive Programming; Müller-Hannemann & Schirra
(eds.), Algorithm Engineering; Fenwick 1994; Bender & Farach-Colton 2000; Khuong & Morin 2017; Mytkowicz et al.
2009; Langdale & Lemire 2019 (simdjson); Kraska et al. 2018; Ferragina & Vinciguerra 2020.
Build the film
python -m videos.cs.cs24.compute # the part's numbers, into .cache/cs24
python tools/build.py cs24 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs24 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs24. Setup: see the course page. Source of these notes: the README and the scenes' narration.