12.4 Discrete math 2 problem set, part a: DAGs, modular arithmetic, hashing
The bigram model at the start of AI Engineering needed no graph: its gradient was a count. Once the system gains an autograd engine, in Tensor, broadcasting backward, and no_grad, backward is only correct if every node’s gradient is complete before it is passed on to that node’s inputs, which means visiting the graph in reverse topological order. Graphs, DAGs, and an iterative topological sort builds that order with an iterative depth-first search, because a recursive one crashes on the -node chains that long sequences produce.
Concepts from other sections (25)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- bigram model: a language model that predicts the next token from the current token alone, stored as a table. Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- Reverse topological order: an ordering in which every node comes before the nodes it was computed from. Read more: 14.2 Scalar reverse mode: the Value graph
- Depth-first search (DFS): traversal that follows one path as far as possible before backtracking, using a stack. Read more: 18.6 Graph as an adjacency list in Programming and Algorithms
- PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- FNV-1a: a byte hash that xors each byte in and then multiplies by a fixed prime mod . Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- Bijection: a function that is both injective and surjective, and so has an inverse. Read more: 11.3.4 Relations, functions, and validation
- Directed graph: a set of vertices and a set of ordered pairs of vertices called edges. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
- In-degree: the number of edges entering a vertex, counting parallel edges separately. Read more: 18.6 Graph as an adjacency list in Programming and Algorithms
- Adjacency matrix: a table whose entry records whether, or with what weight, an edge joins and ; it gives edge lookup at space, which suits dense graphs. Read more: Chapter 8: Graphs in Programming and Algorithms
- Greatest common divisor (GCD): , the largest integer dividing both and ; has a multiplicative inverse modulo exactly when . Read more: Chapter 12: Discrete Math 2
- Post-order: the order in which a depth-first search finishes vertices. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
- Reverse mode: automatic differentiation that records the computation and walks it backward once from the output, pushing adjoints into inputs. Read more: 14.2 Scalar reverse mode: the Value graph
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Equivalence relation: a reflexive, symmetric, transitive relation; its classes partition the set. Read more: 11.3.4 Relations, functions, and validation
- LCG: a generator that steps . Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- Birthday bound: the observation that keys in buckets start to collide at . Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences
- Block hash: a hash over token ids chained with the parent hash, independent of the payload format. Read more: 12.5 The KV format v2 migration in Systems Engineering
- Linearity of expectation: , which holds even when and are dependent; it is the main tool for analysing randomized algorithms, such as the coupon collector’s expected draws. Read more: Chapter 13: Probability and Statistics
- Pigeonhole principle: inputs cannot produce more than distinct outputs, so for equal sizes injective and surjective coincide. Read more: 11.2 Injective, surjective, bijective: the GPT-2 byte map
- Injective: no two inputs share an output; for a dict, no value appears twice. Read more: 11.2 Injective, surjective, bijective: the GPT-2 byte map
- Bezout’s identity: for any integers and there are integers and with ; the extended Euclidean algorithm finds them. Read more: Chapter 12: Discrete Math 2
- SplitMix64: the mixer used to derive child seeds that depend only on the seed and the purpose. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- MinHash: estimating Jaccard similarity by how often the minima of random permutations agree. Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences
- Bloom filter: a bit array with hashes per key that never misses an inserted key and has a tunable false-positive rate. Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences
- Computation graph: a graph with one node per value and an edge from each value to the values it was computed from. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
At the same point, Modular arithmetic, hashing, and PCG32 in Python builds PCG32, the random generator every later section draws from, and FNV-1a, the hash that the Paged KV block pool uses to name KV-cache blocks. Both are arithmetic on 32- and 64-bit words that silently wrap. This problem set builds fluency in directed acyclic graphs, modular arithmetic, and the basic probability of hashing before you read that code. It is a pen-and-paper set with no code to write: 18 problems with exact answers (23 parts in all) and 5 proofs. Problem 20 is the correctness proof of the topological sort, and Problem 22 explains the odd multiplier inside PCG32.
You will need the proof methods, induction, counting, and bijections of the Discrete Math 1 problem set, and the graph and number-theory material of the chapter opening. Every problem is followed by a collapsed worked answer with the final result or a complete model proof, together with the common wrong answers and why they are wrong. Try each problem before opening its answer.
Learning objectives
- Recognize a valid topological order, count the orders of a small DAG, and explain why the order is rarely unique.
- Relate recursion depth to the longest input chain, and prove an iterative DFS correct.
- Compute remainders, inverses, wrapping sums, and rotations on machine words, and prove when is a bijection.
- Compute FNV-1a and a universal hash by hand, and the expected number of colliding pairs in a hash table.
Directed graphs and DAGs
Section titled “Directed graphs and DAGs”The notation is shared by the review and the problems.
| Symbol | Meaning | Type / shape |
|---|---|---|
| a directed graph: nodes , edges | ||
| an edge; in an autograd graph, is an input of | ||
| in-degree (edges into ), out-degree (edges out of ) | integer | |
| adjacency matrix, when | int[n][n] | |
| remainder of on division by , in | integer | |
| divides | relation | |
| greatest common divisor | integer | |
| bitwise XOR | uint64 | |
| number of keys, number of buckets | integer | |
| load factor | real |
A directed graph is a set of nodes and a set of ordered pairs of nodes, the edges. A path is a sequence of edges , and a cycle is a path of length at least 1 that returns to its start. A graph with no cycle is a directed acyclic graph (DAG). Every expression a program evaluates is a DAG: the nodes are values, and when is an input of the operation that makes . A value used twice ( in ) has out-degree 2, which is why a gradient must be summed over consumers. Note that this set draws edges from input to consumer, the forward direction, while the topological-sort section draws them from a node to its parents; the two are the same graph with the arrows reversed.
A topological order lists all nodes so that every edge goes forward: implies is listed before . A graph has one exactly when it is acyclic (Problem 19 proves one direction; Problem 18 gives the other). Topological orders are rarely unique: any two nodes not connected by a path can be swapped. That is why an arbitrary topological sort is judged by the property “every edge goes forward”, never by one specific list. (The implementation in the topological-sort section additionally fixes one particular order, for bit-identical gradients.)
Two algorithms produce one. Kahn’s algorithm keeps the in-degree of every node, repeatedly outputs a node of in-degree 0, and decrements the in-degrees of the nodes it points to. Depth-first search outputs a node after all of its inputs have been output (post-order). Written recursively, DFS uses one stack frame per node on the current path, so its depth is the length of the longest input chain, and Python raises RecursionError past 1000 frames. Written with an explicit stack (Problem 20), its depth is bounded only by memory.
Paths also count. Entry of is the number of paths of length exactly from to , because extends each path of length by one edge. A DAG on nodes has no path longer than edges, so . In reverse mode, the derivative of an output with respect to an input is a sum over all paths between them of the product of the local derivatives along each path: the chain rule of Jacobians, the multivariable chain rule, and numeric JVP/VJP, organized by the graph.
Modular arithmetic
Section titled “Modular arithmetic”Graphs fix the order of computation; modular arithmetic describes what each step of a generator or hash computes. Division with remainder says that for integers and there are unique integers and with and ; write . For negative the remainder is still in : . (C’s % truncates toward zero and returns ; Python’s % returns 3.) Two integers are congruent modulo , , when divides . Congruence is an equivalence relation, and it respects and (Problem 21), so you may reduce after every step.
The multiplicative inverse of modulo is an with ; it exists exactly when . Then multiplication by permutes (Problem 22); when , it maps everything onto multiples of and loses states (Problem 23).
Machine words
Section titled “Machine words”A uint32_t holds bits and its arithmetic is arithmetic modulo : wraps to 1. C, Rust, and Go all expose this (C on unsigned types, Rust with wrapping_add and wrapping_mul, Go on uint32 and uint64), and Python emulates it with & 0xFFFFFFFF. A logical shift right by drops the low bits and fills with zeros. A rotation right by moves bit to bit , so no bit is lost: in C, (x >> r) | (x << ((32 - r) & 31)). PCG32 advances a 64-bit LCG state with odd and odd , then outputs a 32-bit word built with a XOR-shift and a rotation by the state’s top 5 bits (course/contracts/spec/pcg32.md).
FNV-1a 64 hashes bytes by starting at the offset basis and setting with the prime . The order matters: FNV-1 multiplies first and XORs second, and gives a different value.
Hashing and load factor
Section titled “Hashing and load factor”A hash table with buckets stores a key in bucket . Chaining keeps a list per bucket. The load factor is the average list length. Under simple uniform hashing (each key lands in each bucket with probability , independently), an unsuccessful lookup computes the hash and scans one whole chain, probes on average. A universal family such as with a prime larger than any key and random , makes any two keys collide with probability at most about , whatever the keys.
Collisions are common long before the table fills. Each of the pairs of keys collides with probability , and expectation is linear, so the expected number of colliding pairs is . With and it is already about . Part b of the problem set turns this into the birthday bound.
Working two examples by hand
Section titled “Working two examples by hand”The two examples here are siblings of Problems 3 and 22, not problems of the set. First, count the topological orders of the graph with edges , , on nodes .
needs and before it, and needs , so is last and is third: positions 3 and 4 are forced. Positions 1 and 2 hold and in either order. That gives 2 orders, and . In general, count by cases on which source comes first, as in Problem 3; never assume the order is unique.
Second, claim: is a bijection of , and is not. The method is direct computation, then the general reason. The images under of are : all eight values, each once, so it is a bijection. The reason is , and , so multiplying by 5 is undone by multiplying by 5 again. Under the images are : two values, because and every image is a multiple of 4. A multiplier sharing a factor with the modulus collapses states. That is the content of Problems 22 and 23, and the reason an LCG on 64-bit words uses an odd multiplier.
How the problems work
Section titled “How the problems work”Answers are exact integers or fractions (, ), written in decimal. Lettered parts share one answer block. The tag after each problem says what kind of answer is expected.
Throughout, is the directed graph on nodes with edges , , , , . An edge means ” is an input of ”, so must be computed before .
Problems on graphs and DAGs
Section titled “Problems on graphs and DAGs”The first nine problems work on and two small companions. They build up from degrees and orders to counting paths and the recursion depth that motivates an iterative traversal.
Problem 1. In : (a) what is the in-degree of node 5? (b) What is the out-degree of node 2? [number]
Answer
(a) , (b) . (a) Edges into 5: and . (b) Edges out of 2: and . In-degree drives Kahn’s algorithm; out-degree is how many consumers a gradient sums over. A common mistake is 0 for either part, which reads the other degree (node 5 has out-degree 0, node 2 in-degree 0).
Problem 2. (a) Is a topological order of ? (b) Is ? [bool]
Answer
(a) True, (b) false. Check each edge goes forward. (a) , , , , all go from an earlier to a later position. (b) goes backward: 3 is at position 3 and 1 at position 4. One backward edge is enough to reject an order, and checking the edge property is how a correct topological sort is recognized.
Problem 3. How many topological orders does have? [number]
Answer
. Node 5 needs both 3 and 4, so it is last. Among , node 3 must follow 1 and 2, and 4 must follow 2. By cases on the first node, which must be a source (1 or 2): starting with 1, then 2 is forced (3 and 4 both wait on 2), then 3 and 4 in either order: 2 orders. Starting with 2, the remaining need only 1 before 3: the orders ; ; : 3 orders. Total 5. Common mistakes: 1, which assumes the order is unique, and , which counts every permutation.
Problem 4. Kahn’s algorithm starts from the in-degree of every node. Give the in-degrees of nodes of in that order. [vector]
Answer
. Count incoming edges: nodes 1 and 2 have none, 3 has two (from 1 and 2), 4 has one (from 2), 5 has two (from 3 and 4). Kahn’s algorithm starts from the zeros, 1 and 2. A common mistake is , the out-degrees, which would start from the sink 5.
Problem 5. How many directed paths lead from node 2 to node 5 in ? (In reverse mode, the gradient of node 5 with respect to node 2 is a sum with one term per path.) [number]
Answer
. and . The chain rule gives as the sum of two products of local derivatives, one per path, which is why reverse mode adds gradients from every consumer.
Problem 6. Is the graph with edges , , , a DAG? [bool]
Answer
False. is a directed cycle. The extra edge does not matter: one cycle is enough.
Problem 7. The chain has adjacency matrix with when is an edge. Entry of counts the paths of length from to . Give (a) and (b) . [matrix]
Answer
(a) , (b) . The paths of length 2 are and , so . The only path of length 3 is . : a DAG’s adjacency matrix is nilpotent. Common mistakes: itself for (a), (paths reversed), and the zero matrix for (b), which is .
Problem 8. The autograd graph of has nodes , , , and . Backward must visit a node only after every node that consumes it. Which order is valid for backward? [choice]
(a) (b) (c) (d)
Answer
(a). Backward visits a node only after all of its consumers. consumes and ; consumes and . So first, then ; must come after both and . Order (a), , satisfies this. Common mistakes: (b) is the forward order; (d) visits before its consumer , so ‘s gradient would be passed on before ‘s contribution is added; (c) visits before its consumer .
Problem 9. A recursive depth-first search that starts at the last node of a chain of nodes and recurses into each node’s input makes how many nested calls at its deepest point, counting the first call? (Python’s default recursion limit is 1000.) [number]
Answer
. The search starts at the last node and recurses into its input, one call per node down the chain, so the deepest point has all calls on the stack, 100 times Python’s limit. This is why the topological sort in Graphs, DAGs, and an iterative topological sort uses an explicit stack. Common mistakes: 1000 is the limit, not the depth; 17 would be the depth of a balanced tree, not a chain.
Problems on modular arithmetic and hashing
Section titled “Problems on modular arithmetic and hashing”The next eight problems move from remainders and inverses to the word-level operations of PCG32 and FNV-1a, and finish with hash-table load and collisions. Here is the remainder in , also for negative .
Problem 10. (a) . (b) . [number]
Answer
(a) , (b) . (a) . (b) , and the remainder must be in . A common mistake is , which is C’s truncating % (); Python’s % gives 3. Answering 2 for (b) drops the sign.
Problem 11. Give the multiplicative inverse of 3 modulo 11: the with . [number]
Answer
. . The inverse exists because . A common mistake is , the rational inverse, which is not an element of .
Problem 12. A uint32_t adds modulo . What is ? [number]
Answer
. , so the sum is . A common mistake is 4294967297, which does not wrap: that is what a Python port of PCG32 produces without & 0xFFFFFFFF.
Problem 13. PCG32’s output step rotates a 32-bit word right. Rotating right by bits moves bit to bit . Give the rotation of (bits 31 and 0 set) right by 1 bit, as a decimal number. [number]
Answer
. Bit 31 moves to bit 30 and bit 0 moves to bit , so the result has bits 31 and 30 set: . This rotation is the last step of PCG32’s XSH-RR output (pcg32.md). Common mistakes: is a logical shift, which loses the low bit; 3 rotates left.
Problem 14. FNV-1a 64 starts at and, for each byte , sets , where is bitwise XOR. Give the FNV-1a 64 hash of the one-byte string a (byte 97), as a decimal number. [number]
Answer
. XOR first: the offset basis is 0xcbf29ce484222325, and , so . Then multiply by the prime and reduce modulo : (0xaf63dc4c8601ec8c). A common mistake is 12638153115695167422, the FNV-1 value (multiply, then XOR): the KV block hashes of the Paged KV block pool would then disagree with every other implementation.
Problem 15. A hash table with chaining has buckets and holds keys. (a) Give its load factor . (b) Under simple uniform hashing, an unsuccessful search hashes once and then scans a whole chain; its expected cost is probes. Give it. [number]
Answer
(a) , (b) . (a) . (b) : one probe for the hash and on average for the chain. Common mistakes: for (a), and for (b), which forgets the hash computation itself.
Problem 16. For the universal hash with , , , , give . [number]
Answer
. , , . A common mistake is 3, which is and skips the reduction modulo , so the family is no longer universal.
Problem 17. keys are hashed independently and uniformly into buckets. What is the expected number of pairs of keys that share a bucket? [expr in n, m]
Answer
. Let be 1 when keys share a bucket; . By linearity of expectation, , with no independence needed between pairs. Common mistakes: is the load factor, and counts ordered pairs including each key with itself.
Proofs
Section titled “Proofs”The last six problems are proofs, plus one closing check. Problems 18 and 19 together prove that a topological order exists exactly when the graph is acyclic; Problem 20 proves the iterative DFS correct; Problems 21 to 23 justify reducing after every step and the odd multiplier of an LCG.
Problem 18. Prove that every finite, nonempty directed acyclic graph has a node with in-degree 0. [proof]
Answer
Claim: every finite, nonempty directed acyclic graph (a DAG) has a node with in-degree 0.
Method: contradiction, with the pigeonhole principle.
Let have nodes and suppose every node has in-degree at least 1, so every node has at least one input. Start at any node , pick an input of it (an edge ), then an input of , and so on: each step is possible because every node has an input. After steps we have nodes with edges .
There are only distinct nodes, so by pigeonhole for some . Then is a directed cycle, contradicting that is acyclic.
So some node has in-degree 0. (Kahn’s algorithm relies on this at every step: removing a source from a DAG leaves a DAG, which again has a source.)
Model proof also in q18.md.
Problem 19. Prove that a directed graph that has a topological order has no directed cycle. [proof]
Answer
Claim: if a directed graph has a topological order, then has no directed cycle.
Definitions: a topological order is a listing of all nodes, with position , such that every edge has . A directed cycle is a sequence of edges with .
Method: contradiction.
Suppose has a topological order and a directed cycle . Applying the order property to each edge of the cycle gives , and by transitivity of , , which is false.
So has no directed cycle. (With Problem 18 the converse also holds: repeatedly removing a node of in-degree 0 lists any DAG in topological order.)
Model proof also in q19.md.
Problem 20. The section Graphs, DAGs, and an iterative topological sort orders the autograd graph with an iterative depth-first search. Each node has a finite list of inputs, inputs(v), and the graph reachable from the root is acyclic:
order = []; seen = {root}; stack = [(root, iterator over inputs(root))]while stack is not empty: (v, it) = top of stack if it yields an input u that is not in seen: add u to seen; push (u, iterator over inputs(u)) else if it is exhausted: pop (v, it); append v to orderreturn orderProve that every node reachable from the root appears in order exactly once, and after all of its inputs. (Backward then walks order in reverse.) [proof]
Answer
Claim: for a root whose reachable graph is finite and acyclic, the iterative DFS appends every reachable node to order exactly once, and each node after all of its inputs.
Method: three invariants of the loop, then acyclicity.
(1) At most once. A node is pushed only when it is not in seen, and it is added to seen at that moment (the root at the start), so each node is pushed at most once. A node is appended only when its own stack entry is popped, so it is appended at most once.
(2) Every reachable node is pushed. Induction on , the length of the shortest input path from the root to . For , is the root, pushed at the start. If is an input of a node with , then was pushed by the hypothesis. The loop only pops once its iterator is exhausted, so before that the iterator yielded ; at that moment was either not seen (and is pushed now) or already seen (and was pushed earlier). The loop ends only with an empty stack; each iteration either pushes a node (at most times in total) or advances an iterator or pops, so it terminates, and every pushed node is eventually popped and appended. With (1), every reachable node is appended exactly once.
(3) Inputs first. First a stack invariant: if the stack holds from bottom to top, then each is an input of , because a node is pushed only when the iterator of the node then on top yields it. Write when is an input of ; the invariant says .
Now let be appended. Its iterator yielded every input of , each at a moment when was on top. If was not seen then, it was pushed on top of ; the stack is last in, first out, so was popped and appended before . If was already seen, it was pushed earlier, and either it has already been appended (fine), or it is still on the stack below : with , . In that last case the invariant gives a path , and closes it into a directed cycle, which contradicts acyclicity. ( is impossible too, since would be a cycle.)
So every input of is appended before . Walking order in reverse visits every node before its inputs, which is the order backward needs.
Model proof also in q20.md.
Problem 21. Prove that for all integers and every integer . [proof]
Answer
Claim: for all integers and every integer , .
Definitions: by division with remainder, every integer is for unique integers and with ; is that . Uniqueness implies: if is a multiple of , then (writing gives with the same ).
Method: direct.
Write and with and . Then , a multiple of . By the uniqueness remark, , which is the claim. This is why a hash or an RNG may reduce after every step instead of once at the end, and why a uint64_t that wraps computes the right value modulo .
Model proof also in q21.md.
Problem 22. Prove that if , then is a bijection of . (This is why the LCG step inside PCG32 never merges two states: its multiplier is odd.) [proof]
Answer
Claim: if , then is a bijection of .
Method: show is injective; an injective map from a finite set to itself is a bijection, because its image has as many elements as the set itself.
Suppose for . Then and have the same remainder, so divides .
Since , Bezout’s identity gives integers with . Multiply by : . Both terms on the right are multiples of , so divides (this is Euclid’s lemma).
But , so , and the only multiple of in that range is 0. So , is injective, and therefore a bijection of .
For this says any odd multiplier permutes the 64-bit states: PCG32’s LCG step never sends two states to one. Problem 23 shows what goes wrong when .
Model proof also in q22.md.
Problem 23. Is a bijection of ? [bool]
Answer
False. , so every image is even: only the 8 values are reached, and for example . Two inputs share each image. This is the hypothesis of Problem 22 failing, and why an LCG’s multiplier must be odd.
What can go wrong
Section titled “What can go wrong”The problems were chosen so that each common mistake shows up as a wrong answer. The table collects those mistakes, what they look like in code, and the habit that avoids them.
| Pitfall | Symptom | How to avoid it |
|---|---|---|
| Testing for one specific topological order | a correct toposort fails on a valid order | check that every edge goes forward instead of comparing with one list (Problems 2, 3) |
| Swapping in-degree and out-degree | Kahn’s algorithm starts from sinks and emits nothing | count edges into each node (Problem 4) |
| Backward in forward order, or a shared node before one of its consumers | a gradient used before every consumer added to it | visit a node only after all of its consumers: reverse topological order (Problem 8) |
| Recursing over a long chain | RecursionError at depth 1000 on a long sequence | use an explicit stack, whose depth is bounded only by memory (Problems 9, 20) |
Using C’s truncating % for a negative operand | a negative bucket index | take the remainder in , as Python’s % does (Problem 10) |
| Forgetting to wrap at the word size | a Python port of PCG32 diverges from C after one step | reduce modulo after every operation (Problems 12, 21) |
| Shifting instead of rotating | PCG32 output loses high bits | OR the shifted-out bits back in at the top (Problem 13) |
| Multiplying before XOR in FNV-1a | block hashes that disagree with every other implementation | XOR the byte in first, then multiply (Problem 14) |
| A multiplier sharing a factor with the modulus | the generator or hash collapses onto a fraction of its states | check ; for , use an odd multiplier (Problems 22, 23) |
Where this leads
Section titled “Where this leads”Looking back, Problems 18 to 22 rest on the induction, pigeonhole, and injective-and-surjective arguments of the Discrete Math 1 problem set. Looking forward, Graphs, DAGs, and an iterative topological sort implements toposort for backward, iterative so that a -deep chain works, and Problem 20 is its correctness proof. Modular arithmetic, hashing, and PCG32 in Python implements PCG32, SplitMix64, FNV-1a, and universal_hash. In AI Engineering, Tensor, broadcasting backward, and no_grad walks the topological order in reverse and sums gradients over consumers, and the Paged KV block pool names KV blocks by chained FNV-1a 64 hashes. Part b of the problem set builds trees, birthday bounds, MinHash, and Bloom filters on Problems 15 to 17.
Further reading
Section titled “Further reading”- Hammack, Book of Proof, chapters 11 and 12.
- Cormen et al., Introduction to Algorithms, chapter 11 (hashing) and section 22.4 (topological sort).
- O’Neill, “PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms” (2014), sections 4 and 6.
Key terms
Section titled “Key terms”- DAG: a directed graph with no directed cycle; every computation graph is one.
- In-degree, out-degree: the number of edges into and out of a node.
- Topological order: a listing of the nodes in which every edge goes forward.
- Kahn’s algorithm: repeatedly output a node of in-degree 0 and decrement its successors’ in-degrees.
- Congruence modulo : when divides .
- Multiplicative inverse: an with , which exists exactly when .
- Rotation: a shift that moves the bits falling off one end back in at the other.
- Load factor: , the average chain length of a hash table.
Summary
Section titled “Summary”- A computation graph is a DAG; a topological order lists every node after its inputs, it is rarely unique, and backward walks it in reverse (Problems 2, 3, 8).
- Recursion depth equals the longest input chain, so a recursive traversal of a -node chain dies at Python’s limit of 1000; the iterative DFS of Problem 20 does not (Problem 9).
- Fixed-width integers are arithmetic modulo : addition wraps, rotation moves bits around the word, and permutes the words exactly when is odd (Problems 12, 13, 22, 23).
- FNV-1a XORs a byte in, then multiplies; swapping the two steps gives FNV-1, a different hash (Problem 14).
- With keys in buckets the expected number of colliding pairs is , which is why collisions appear long before the table is full (Problem 17).
- Model proofs for Problems 18 to 22 are also in
course/solutions/solve/S-M06a/.