Ch.10: Algorithms: How Topological Sorting Finds an Order

Outline

Transcript

0:00 Imagine a build list that says run tests, build the program, generate the source. Follow it literally and the tests fail before there's anything to run. The steps aren't missing. They're in the wrong order. And topological sorting can solve that from one kind of rule: this task has to finish before that one. With those before-and-after rules, imagine we're serving a cake. Prepare ingredients before mixing, mix before baking, bake before serving. Set the table before serving too. But setting the table doesn't have to wait for baking.

0:31 Some tasks have an order, others don't. Now turn those tasks into dots, called nodes. Draw an arrow for each must-happen-first rule. Those dots and arrows form a directed graph. Ingredients points to mix. The arrow means ingredients must finish first. Keep that direction in mind: prerequisite to the thing that needs it. With that arrow direction, our chain is ingredients, mix, bake, serve. Table also points to serve. A topological order puts the starting task of every arrow before its destination.

1:03 So table first or table after baking could both obey the rules. Yes. Alphabetical order would be impressively unhelpful here. Bake before ingredients. Very efficient way to make an empty oven hot. But how do we find the good order without guessing? First, Kahn's algorithm counts each task's prerequisites. MIT's notes describe this zero-count method. We'll keep ready tasks in a queue. Ingredients needs zero. Table needs zero. Mix needs one, ingredients. Bake needs one, mix. Serve needs two, bake and table. Two matters.

1:36 A finished cake doesn't mean we're ready to serve if the table isn't set. Exactly. Keep those counts in a little table. Then keep a ready collection containing the zero-count tasks, and an output list, initially empty. That's all the changing state we need. Counts, ready, output. My first thought is to keep rescanning the whole task list for something available. This ready collection saves us that search each time. Now ingredients and table are ready. Suppose we pick table first instead. Would that break anything? Either is legal.

2:07 Let's use a queue: take from the front, add newly ready tasks at the back. Start with ingredients, then table. That's our chosen tie-break, not a rule imposed by the graph. Take ingredients out of ready and put it in output. We're constructing an order on paper here, so that selection means we can stop counting ingredients as an unfinished prerequisite. Follow its outgoing arrow to mix. Mix's count falls from one to zero. Add mix at the back of ready. The queue is now table, then mix. Next, take table. Output now reads ingredients, table.

2:40 Follow table's arrow to serve: serve's count falls from two to one. Like opening one of two locks on serve. Table's lock is open, but bake's is still closed. So serve keeps waiting? Yes. The count is still one, because bake isn't in the output yet. Only zero gets into ready. Right. The count saves us rereading every prerequisite. One remaining means there's still a lock to open. With table selected, ready contains only mix. Take mix, append it to output, and follow its arrow to bake. Bake goes from one to zero, so bake joins ready.

3:15 Take bake next. Its arrow reduces serve from one to zero. Now serve joins ready. Take serve, and there are no outgoing arrows to update. Ready is empty. Output is ingredients, table, mix, bake, serve. All five tasks made it. We found an order. And setting the table after baking would also be fine. If we chose ready tasks differently, the same constraints could produce that other valid list. So notice what we never did: put a task in output while one of its prerequisites was missing. Initially zero means no prerequisites at all.

3:49 Later zero means every prerequisite has already been selected. And when we select a task, we update only the tasks its arrows point to. No reason to change anything else. Right. That keeps the counts honest. Each count means unfinished prerequisites, throughout the process. A task can enter ready only once, when its count first reaches zero. It also leaves at most once. So this isn't lucky ordering. Every choice is safe because of the same condition. I find that more reassuring than looking at the final list and hoping we didn't miss an arrow. Let's say someone changes the instructions: add an arrow from serve back to mix.

4:30 Now mixing must wait until serving finishes. Then mix needs ingredients and serve, so its initial count is two. Ingredients and table still start ready. Selecting ingredients lowers mix to one. Selecting table lowers serve to one. And now nothing is ready. Mix is waiting for serve, serve for bake, bake for mix. Each would need another member of that loop to go first. That's a directed cycle. Under these strict before-and-after rules, no member can go first. We didn't just choose a bad order; there is no complete valid order.

5:05 But I think there's a trap in that stopping condition. The queue emptied after our successful cake too. How do we tell success from getting stuck? Compare output size with task count. All five means done. With only two selected, we got stuck. Every remaining task still needs another remaining task, or it would be ready. For instance, mix waits for serve, serve for bake, bake for mix. We're back at mix. In any finite collection, a chain of unfinished tasks all waiting on one another must eventually revisit a task.

5:38 That repeated waiting is the cycle. And somewhere in that remainder isn't the same as everywhere. For example, add a clean-up task after serve. It stays blocked too, outside the mix, bake, serve cycle. Ah, so the leftover list includes work waiting behind the knot. We'd need another search to identify exactly which tasks form the loop. Now our paper trace raises another question about unfinished work. Selecting ingredients isn't finishing the actual job. When can a real worker unlock mixing? Yes, our algorithm is making a plan.

6:12 A real executor must wait for the prerequisite to finish successfully before lowering dependent counts. Started isn't done. That distinction is explicit in Python's graphlib: get ready tasks, do the work, then mark them done. Its docs and the algorithm notes are linked in the description. And a schedule chooses who starts when. Suppose mixing takes 20 minutes and setting the table takes two. Once both are ready, one worker needs 22 minutes; two can overlap them in 20. A valid order alone doesn't choose that schedule.

6:44 Now that we can run the sort, how much work does it take? Do we search all five tasks after every selection? No. Store each task's dependents in a list and go straight to them. Each task enters and leaves ready at most once. Count each arrow during setup, then follow it at most once as its prerequisite leaves. So the bookkeeping grows with tasks plus arrows, rather than trying combinations of orders. In our cake graph that's five task records and four arrows. Yes. Big O names how work grows as inputs grow.

7:19 Here it's O of V plus E: V counts tasks, E counts arrows. Those stored records also make space grow with that sum. And our simple queue can add and remove tasks in constant time. If I always wanted the alphabetically first ready task instead, would that change the work? We'd pay for maintaining that order. After ingredients, our queue chooses table before newly ready mix; alphabetical selection chooses mix. Both are valid. A priority queue can implement that preference, but its ordering work is extra to the simple queue's bound.

7:52 Same algorithm, different setting: for example, generating code, turning it into a runnable program, then testing it. Each step must finish before the next can start. Nodes change names, arrows keep the same meaning, and counts work exactly as before. But suppose we omit the first arrow. The build could try to convert code that hasn't been generated. It could. The order obeys the graph we gave it. It can't discover a dependency we failed to declare. I'd check the input constraints before blaming the sort.

8:22 That's useful beyond builds. Course prerequisites, data-processing stages, any task graph with genuine prerequisites. Draw the actual rules, then let the algorithm do the bookkeeping. Finally, hand me the cake graph again. I count unfinished prerequisites, put zero-count tasks in ready, take one into output, and update only its dependents. Repeat until ready is empty. Then compare output with the full task list. All present means a valid order. Tasks left means a cycle prevents a complete order, even if some leftovers only wait behind it.

8:55 And two ready tasks aren't an ambiguity to fix. They're freedom the constraints allow. That's topological sorting: finding an order without inventing rules the tasks don't have. Thanks for listening to Learning Podcasts.