{"id":"task-dependency-order","title":"Task Dependency Order","difficulty":"medium","patterns":["topological-sort"],"primaryConcept":"graph-toposort-ordering","concepts":["graph-toposort-ordering"],"problemForm":"application","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"graph-edges","primaryParam":"dependencies","sizeMetric":"nodes-plus-edges","constraints":["dag"],"secondaryParams":{"numTasks":{"strategy":"scale-with-primary"}},"sizes":[8,16,32,64]},"description":"You have `numTasks` tasks labeled from `0` to `numTasks - 1`. Each dependency `[before, after]` means task `before` must be completed before task `after`.\n\nReturn the deterministic order produced by a FIFO topological frontier: seed initially available tasks in increasing label order, then append newly unlocked tasks as their dependency edges are scanned. If no valid order exists because the dependencies contain a cycle, return an empty list.","examples":[{"input":"numTasks = 4, dependencies = [[0,1],[0,2],[1,3],[2,3]]","output":"[0,1,2,3]","explanation":"Task 0 unlocks tasks 1 and 2; both must finish before task 3."},{"input":"numTasks = 2, dependencies = [[0,1],[1,0]]","output":"[]","explanation":"The two tasks depend on each other, so no valid order exists."}],"constraints":[{"id":"1-numtasks-10-5","text":"1 <= numTasks <= 10^5","check":{"kind":"valueRange","target":"numTasks","selector":"value","min":1,"max":100000}},{"id":"0-len-dependencies-10-5","text":"0 <= len(dependencies) <= 10^5","check":{"kind":"sizeRange","target":"dependencies","measure":"arrayLength","min":0,"max":100000}},{"id":"dependencies-i-length-2","text":"len(dependencies[i]) == 2","check":{"kind":"shape","target":"dependencies","shape":"tupleArray","tupleLength":2}},{"id":"0-before-after-numtasks","text":"0 <= before, after < numTasks"},{"id":"before-after","text":"before != after"}],"starterCode":"class Solution:\n    def findTaskOrder(self, numTasks: int, dependencies: list[list[int]]) -> list[int]:\n        # Your code here\n        pass","functionName":"findTaskOrder","testCases":[{"id":"1","input":{"numTasks":4,"dependencies":[[0,1],[0,2],[1,3],[2,3]]},"expected":[0,1,2,3],"description":"Diamond-shaped dependency graph."},{"id":"2","input":{"numTasks":2,"dependencies":[[0,1],[1,0]]},"expected":[],"description":"Cycle means no valid order."},{"id":"3","input":{"numTasks":3,"dependencies":[]},"expected":[0,1,2],"description":"No dependencies, so the initial queue emits tasks in label order."},{"id":"4","input":{"numTasks":5,"dependencies":[[0,2],[1,2],[2,3],[2,4]]},"expected":[0,1,2,3,4],"description":"Two independent roots unlock a shared dependent task."},{"id":"5","input":{"numTasks":4,"dependencies":[[1,2]]},"expected":[0,1,3,2],"description":"Independent tasks are queued in label order before later unlocked tasks."},{"id":"h1","input":{"numTasks":6,"dependencies":[[0,3],[1,3],[2,4],[3,5],[4,5]]},"expected":[0,1,2,3,4,5],"description":"Multiple frontier waves."},{"id":"h2","input":{"numTasks":3,"dependencies":[[0,1],[1,2],[2,1]]},"expected":[],"description":"A cycle in one component prevents a full order."},{"id":"h3","input":{"numTasks":5,"dependencies":[[0,2],[1,2],[1,3],[4,3]]},"expected":[0,1,4,2,3],"description":"Multiple initial tasks feed a later unlocked task."},{"id":"h4","input":{"numTasks":4,"dependencies":[[0,1],[1,0],[2,3]]},"expected":[],"description":"Any cycle makes a full order impossible."},{"id":"h5","input":{"numTasks":5,"dependencies":[[0,2],[0,3],[1,3],[2,4],[3,4]]},"expected":[0,1,2,3,4],"description":"A FIFO frontier emits tasks in a deterministic unlock order."},{"id":"topup-independent-frontier","input":{"numTasks":5,"dependencies":[[0,3],[1,3],[2,4]]},"expected":[0,1,2,3,4],"description":"Multiple independent tasks unlock two later tasks."},{"id":"topup-cycle-empty-order","input":{"numTasks":3,"dependencies":[[0,1],[1,2],[2,0]]},"expected":[],"description":"A dependency cycle produces no valid task order."}],"hints":[{"level":1,"content":"Track how many unfinished prerequisites each task still has."},{"level":2,"content":"Start with tasks whose indegree is zero."},{"level":3,"content":"Each time a task is emitted, decrement the indegree of the tasks it unlocks."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"try-permutations","name":"Try every task order","summary":"Generate possible task permutations and check dependencies afterward.","decisionReason":"numTasks orders grow factorially, and each candidate still has to be checked against dependency pairs. A failed order does not reuse the fact that a task remains blocked by an unmet predecessor.","complexity":{"time":"O(V!)","space":"O(V)"},"tradeoffs":["Runs in O(V!) time and uses O(V) space."],"isOptimal":false},{"id":"kahn","name":"Kahn's topological sort","summary":"Build indegrees, seed zero-indegree tasks, then process the frontier.","decisionReason":"Indegree counts the unmet dependencies for each task, and the FIFO frontier contains exactly tasks whose count is zero. Scanning dependency edges as tasks finish gives the deterministic order and exposes cycles when output is short.","complexity":{"time":"O(V + E)","space":"O(V + E)"},"tradeoffs":["Runs in O(V + E) time and uses O(V + E) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"calculate-indegree","title":"Initialize indegrees","description":"Create adjacency and indegree state for every task.","commonMistakes":["Only storing outgoing edges","Making the indegree array too short"],"hint":"Use one adjacency list and one indegree count per task.","semanticSpec":{"intent":"Initialize graph relation state and indegree counters.","doneWhen":"The solution creates adjacency storage and an indegree array sized by numTasks.","shouldFailWhen":"This step should fail if indegree state is missing.","roles":["adjacency","indegree"],"mustProve":["Indegree state is initialized for the task set."],"mustNotAccept":["Only scanning dependencies without persistent counters."],"equivalentVariants":["Use arrays, lists, or maps for adjacency and indegree."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]}},{"id":"populate-graph","title":"Populate graph","description":"Read each dependency edge, add it to adjacency, and increment the dependent task's indegree.","commonMistakes":["Reversing the dependency direction","Forgetting to increment indegree"],"hint":"`before` points to `after`, and `after` gains one prerequisite.","semanticSpec":{"intent":"Build the directed dependency graph and its indegree counts from input edges.","doneWhen":"Every dependency appends an outgoing neighbor and increments that neighbor's indegree.","shouldFailWhen":"This step should fail if edges do not update both adjacency and indegree.","roles":["dependency edge","adjacency","indegree"],"mustProve":["Input edges populate relation buckets and indegree counters."],"mustNotAccept":["Counting edges without storing outgoing neighbors."],"equivalentVariants":["Use a dictionary/list adjacency representation with parallel indegree state."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"populate-graph","readMode":"graph-value-query-v1"}]}},{"id":"initialize-queue","title":"Seed zero-indegree queue","description":"Add every task with no prerequisites to the frontier queue.","commonMistakes":["Starting from only task 0","Adding tasks whose indegree is not zero"],"hint":"Scan all task labels and enqueue those with indegree 0.","semanticSpec":{"intent":"Initialize the Kahn frontier with all currently unlocked tasks.","doneWhen":"The solution scans tasks and enqueues those with zero indegree.","shouldFailWhen":"This step should fail if the frontier is not seeded from indegree values.","roles":["queue","indegree"],"mustProve":["Zero-indegree tasks are added to the work queue."],"mustNotAccept":["Starting from an arbitrary single task."],"equivalentVariants":["Use a list with a head index or a deque."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]}},{"id":"process-queue","title":"Emit task order","description":"Process queued tasks and append each emitted task to the answer order.","commonMistakes":["Processing the queue but never recording the order","Using stack order after choosing FIFO frontier processing"],"hint":"Each popped task becomes the next task in the order.","semanticSpec":{"intent":"Turn the zero-indegree frontier into an output order.","doneWhen":"The loop removes queued tasks and appends them to the result order.","shouldFailWhen":"This step should fail if processed tasks are not recorded.","roles":["queue","order"],"mustProve":["A task taken from the frontier is appended to the result order."],"mustNotAccept":["Returning the queue itself without processing dependencies."],"equivalentVariants":["Use destructive pops or a head index over a list queue."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"records_topological_order","scope":"process-queue","readMode":"graph-value-query-v1"}]}},{"id":"update-neighbors","title":"Unlock neighbors","description":"For each emitted task, decrement its neighbors' indegrees and enqueue newly unlocked tasks.","commonMistakes":["Not decrementing indegree","Enqueuing neighbors before their indegree reaches zero"],"hint":"A neighbor is ready only when all prerequisites have been emitted.","semanticSpec":{"intent":"Advance the topological frontier through outgoing dependency edges.","doneWhen":"The loop decrements neighbor indegrees and enqueues neighbors whose indegree becomes zero.","shouldFailWhen":"This step should fail if neighbors are not unlocked from processed tasks.","roles":["current task","neighbor","indegree","queue"],"mustProve":["Neighbor indegrees are decremented and zero-indegree neighbors are enqueued."],"mustNotAccept":["Appending every neighbor without checking indegree."],"equivalentVariants":["Use any queue representation as long as zero-indegree neighbors reenter the frontier."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"updates_topology_neighbors","scope":"update-neighbors","readMode":"graph-value-query-v1"}]}},{"id":"check-cycle","title":"Check completion","description":"Return the order only if every task was emitted; otherwise return an empty list.","commonMistakes":["Returning a partial order when a cycle exists","Checking dependency count instead of emitted task count"],"hint":"A valid topological order must contain exactly numTasks tasks.","semanticSpec":{"intent":"Use the output length to reject cyclic dependency graphs.","doneWhen":"The method returns the order when its length equals numTasks, otherwise [].","shouldFailWhen":"This step should fail if a partial order can be returned after a cycle.","roles":["order","task count","cycle check"],"mustProve":["The returned order is gated by the number of emitted tasks."],"mustNotAccept":["Returning a partial order without checking completion."],"equivalentVariants":["Compare len(order) with numTasks or track an equivalent completed count."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_topological_order_or_empty","scope":"check-cycle","readMode":"graph-value-query-v1"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"The task","eyebrow":"Read the problem","title":"Put the tasks in a runnable order","workspacePanel":"problem","body":["You have numTasks tasks labeled 0 to numTasks - 1. Each dependency pair [before, after] means task before must finish before task after starts. Return one order that runs every task after the tasks it depends on, or an empty list if no such order exists.","A task becomes runnable only after every dependency before it has finished. A dependency cycle leaves its tasks waiting forever, so no complete order exists."]},{"id":"brute-force","kind":"code-trace","chapter":"The task","eyebrow":"The obvious way","title":"Lay out an order and check every dependency","workspacePanel":"trace","summary":"Take one full ordering of the tasks and validate it against every dependency pair. This whole check repeats for each ordering tried.","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"candidate = [3, 1, 0, 2]\nposition = [0] * numTasks\nfor index in range(numTasks):\n    position[candidate[index]] = index\nvalid = True\nfor before, after in dependencies:\n    if position[before] > position[after]:\n        valid = False","steps":[{"id":"bf-pick","title":"Lay out one candidate ordering","codeLine":1,"summary":"Take a full ordering of all 4 tasks, say [3, 1, 0, 2], one of the orderings the search runs through.","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"3"}}},{"id":"bf-record","title":"Record where each task landed","codeLine":4,"summary":"position[task] is the slot it sits in: task 3 at slot 0, task 1 at slot 1, task 0 at slot 2, task 2 at slot 3.","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"3"}}},{"id":"bf-check-edge","title":"Validate against every dependency","codeLine":7,"summary":"Walk all 4 dependency pairs. Pair [0, 1] needs task 0 before task 1, but this order put 0 at slot 2 and 1 at slot 1, so the check fails and the ordering is rejected.","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"0","highlighted":["1"],"activeEdges":[[0,1]]}}},{"id":"bf-reject","title":"Rejected, so the search lays out the next ordering","codeLine":6,"summary":"This ordering is invalid, so it is thrown away and a fresh ordering is laid out and re-validated against every pair from scratch.","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"1"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const candidate = [3, 1, 0, 2];\nconst position = Array(numTasks).fill(0);\nfor (let index = 0; index < numTasks; index++) {\n    position[candidate[index]] = index;\n}\nlet valid = true;\nfor (const [before, after] of dependencies) {\n    if (position[before] > position[after]) {\n        valid = false;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7,"7":8,"8":9},"statementBundles":{"4":{"startLine":4,"endLine":5},"8":{"startLine":9,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const candidate = [3, 1, 0, 2];\nconst position = Array(numTasks).fill(0);\nfor (let index = 0; index < numTasks; index++) {\n    position[candidate[index]] = index;\n}\nlet valid = true;\nfor (const [before, after] of dependencies) {\n    if (position[before] > position[after]) {\n        valid = false;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7,"7":8,"8":9},"statementBundles":{"4":{"startLine":4,"endLine":5},"8":{"startLine":9,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> candidate = new ArrayList<>(List.of(3, 1, 0, 2));\nint[] position = new int[numTasks];\nfor (int index = 0; index < numTasks; index++) {\n    position[candidate.get(index)] = index;\n}\nboolean valid = true;\nfor (List<Integer> dependency : dependencies) {\n    int before = dependency.get(0);\n    int after = dependency.get(1);\n    if (position[before] > position[after]) {\n        valid = false;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7,"7":10,"8":11},"statementBundles":{"4":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":9},"8":{"startLine":11,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> candidate = new() { 3, 1, 0, 2 };\nList<int> position = Enumerable.Repeat<int>(0, numTasks).ToList();\nfor (int index = 0; index < numTasks; index++) {\n    position[candidate[index]] = index;\n}\nbool valid = true;\nforeach (var item in dependencies) {\n    int before = item[0];\n    int after = item[1];\n    if (position[before] > position[after]) {\n        valid = false;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7,"7":10,"8":11},"statementBundles":{"4":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":9},"8":{"startLine":11,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> candidate{3, 1, 0, 2};\nvector<int> position = vector<int>(num_tasks, 0);\nfor (int index = 0; index < num_tasks; index++) {\n    position[candidate[index]] = index;\n}\nbool valid = true;\nfor (vector<int> item : dependencies) {\n    int before = item[0];\n    int after = item[1];\n    if (position[before] > position[after]) {\n        valid = false;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7,"7":10,"8":11},"statementBundles":{"4":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":9},"8":{"startLine":11,"endLine":13}}}}}},{"id":"brute-force-cost","kind":"case-probe","chapter":"The task","eyebrow":"Count the cost","title":"How many orderings might this try before one passes?","workspacePanel":"visualizer","summary":"The search lays out a fresh full ordering each time, and each ordering is re-checked against every pair.","options":[{"id":"factorial","label":"Up to every arrangement of the tasks, about numTasks! of them","rationale":"There are numTasks! ways to arrange the tasks, and the valid one can be the last one reached. For 4 tasks that is 24 orderings; for 12 it passes 479 million, and each is re-validated against every pair. The constraints allow 100000 tasks, so this never finishes.","isCorrect":true},{"id":"linear","label":"About numTasks, one ordering per task","rationale":"The search ranges over arrangements of all the tasks at once. There are numTasks! full arrangements, far more than numTasks.","isCorrect":false},{"id":"edges","label":"About one per dependency pair","rationale":"A single pass over the pairs only validates one ordering. That validation repeats for each of the numTasks! orderings, so the pairs multiply the cost.","isCorrect":false}],"answer":"Up to numTasks! orderings, each re-validated against every pair. For 4 tasks that is 24, and it explodes well past anything the 100000-task limit allows. The waste is rebuilding and rechecking a whole ordering when most of it was already forced by the dependencies.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cost-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]]},"arrays":[{"name":"one candidate ordering","values":[3,1,0,2]}]}}]}},{"id":"starting-point","kind":"case-probe","chapter":"The task","eyebrow":"Find the first move","title":"With nothing run yet, what makes a task legal to run first?","workspacePanel":"visualizer","summary":"numTasks = 4, dependencies = [[0,1],[0,2],[1,3],[2,3]], and so far you have run nothing.","options":[{"id":"no-unmet","label":"A task that depends on nothing unfinished: here that is task 0","rationale":"Task 0 depends on nothing, so it can run immediately. Tasks 1, 2, and 3 each still wait on a task you have not run, so none of them can go first. The first task must be one whose dependencies are already satisfied.","isCorrect":true},{"id":"lowest-index","label":"The lowest-numbered task, task 0, just because labels start at 0","rationale":"It happens to be task 0 here, but the label is a coincidence. If task 5 were the only one depending on nothing, you would have to start there. What makes a task runnable is having nothing left ahead of it.","isCorrect":false},{"id":"most-needed","label":"The task the most others depend on, since clearing it unlocks the most","rationale":"Task 0 is also the most depended-on here, but a heavily depended-on task could still have its own dependencies and be illegal to start. Runnability comes from what stands before a task.","isCorrect":false}],"answer":"A task that depends on nothing unfinished. Only task 0 qualifies here. The first move is decided by \"nothing left ahead of it.\"","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]]}}}]}},{"id":"count-remaining","kind":"case-probe","chapter":"The task","eyebrow":"Track what unlocks","title":"What should each task remember so you know the moment it becomes runnable?","workspacePanel":"visualizer","summary":"Running task 0 should make tasks 1 and 2 runnable, but task 3 still has to wait.","options":[{"id":"remaining-count","label":"A running count of dependencies it still has waiting","rationale":"Give each task a count of dependencies not yet finished: 0 starts at 0, tasks 1 and 2 at 1, task 3 at 2. Running a task drops that count by one for everything depending on it. A task becomes runnable exactly when its count hits 0, so running 0 sends 1 and 2 to 0 while 3 only drops from 2 to 1.","isCorrect":true},{"id":"done-flag","label":"A single yes-or-no flag for whether the task has run","rationale":"A done flag records the past but cannot tell you when a task turns runnable. Task 3 needs two dependencies finished before it is ready; a lone flag gives no way to know one is done but the other is still missing.","isCorrect":false},{"id":"depth","label":"How deep the task sits below task 0 in the dependency layers","rationale":"Depth alone misleads when a task sits below several chains of different lengths. Task 3 is reachable through both 1 and 2; what decides its turn is how many of its own dependencies remain, not its distance from the start.","isCorrect":false}],"answer":"A count of remaining dependencies per task, here [0, 1, 1, 2]. Running a task decrements that count for each dependent, and a task is runnable the instant its count reaches 0. That single number is what tells tasks 1 and 2 they are ready while task 3 keeps waiting.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"remaining-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"0","highlighted":["1","2"],"activeEdges":[[0,1],[0,2]]}}}]}},{"id":"build-it-bridge","kind":"info","chapter":"Build it","eyebrow":"Set the plan","title":"One number per task decides every move","workspacePanel":"visualizer","body":["Each task carries a count of dependencies it still waits on, here [0, 1, 1, 2] for tasks 0 through 3. A task is runnable the instant that count reaches 0, and running a task lowers the count of everything depending on it.","That readiness rule is enough to drive the whole order. What remains is how to walk it: which task to run next, and how to spread each decrement as tasks come free."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bridge-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"0"},"arrays":[{"name":"remaining dependencies","values":[0,1,1,2]}]}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"Build it","eyebrow":"Pick the route","title":"How should you generate the order?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Now let us compare possible approaches. Which one should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"kahn","name":"Kahn's frontier walk","summary":"Give every task a remaining-dependency count. Start with the count-zero tasks, run them one at a time, and each time a task runs, lower the count of everything depending on it and release any that reach zero.","decisionReason":"This drives the order directly off the remaining-dependency count you just discovered. Each task and each edge is touched once, so it runs in O(V + E) time and O(V + E) space, and the count-zero check makes a cycle obvious: if some task never reaches zero, fewer than numTasks get run.","complexity":{"time":"O(V + E)","space":"O(V + E)"},"tradeoffs":["Each task and edge is processed once, O(V + E) time and O(V + E) space."],"isOptimal":true,"steps":["Count remaining dependencies for every task","Queue every task whose count is already 0 in label order","Take a task from the queue and append it to the order","Lower the count of each dependent task","Queue any dependent that just reached count 0","If fewer than numTasks were run, a cycle exists"]},{"id":"dfs-postorder","name":"DFS post-order with cycle detection","summary":"Walk each task depth-first, and after all of its dependents are placed, prepend it to the order. Track tasks on the current path to catch a cycle.","decisionReason":"This reaches the same O(V + E) cost, but it asks you to manage three task colors and reverse the result by hand, and the recursion stack hides the \"what is runnable now\" question the count answers in plain sight. It also drops the promised label-order seeding. More state to get right for no gain here.","complexity":{"time":"O(V + E)","space":"O(V + E)"},"tradeoffs":["Same O(V + E) cost, but needs path-state coloring and a final reversal."],"isOptimal":false,"steps":["Visit a task, marking it on the active path","Recurse into every dependent task","A dependent already on the path means a cycle","After all dependents finish, prepend the task","Clear the path mark as the recursion unwinds"]},{"id":"brute-force","name":"Try every ordering","summary":"Generate every permutation of the tasks and return the first one that places each task after all of its dependencies.","decisionReason":"It is correct but checks up to n! orderings, far past anything the constraints allow. With numTasks as large as 100000 this never finishes, while the count-driven walk does the same job in one pass.","complexity":{"time":"O(n! * E)","space":"O(n)"},"tradeoffs":["Up to n! permutations, each validated against every edge."],"isOptimal":false,"steps":["Generate every permutation of task indices","Check each permutation against all dependencies","Return the first ordering that satisfies them all","Return an empty list if none works"]}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"}],"edges":[[0,1],[0,2]],"current":"0","highlighted":["1","2"]}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Build it","eyebrow":"Watch it move","title":"Run the ready tasks, then release what they unlock","workspacePanel":"visualizer","body":["Give every task a remaining-dependency count, call it indegree: it starts at [0, 1, 1, 2] for tasks 0 through 3. A queue holds every count-zero task in label order, so it begins with just task 0. The order you return, order, starts empty.","Each round takes one task off the front of the queue, appends it to order, and walks its dependents, lowering each one by one. Any dependent that drops to 0 joins the back of the queue. Predict which task the queue hands you next at each step, and which dependents that releases."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"queue":["0"]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Build it","eyebrow":"Trace the state","title":"Walk the order out of the counts","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"take-0","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"0","queue":["0"]},"arrays":[{"name":"indegree","values":[0,1,1,2]},{"name":"order","values":[]}]}},{"id":"take-1","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"1","visited":["0"],"queue":["1","2"]},"arrays":[{"name":"indegree","values":[0,0,0,2]},{"name":"order","values":[0]}]}},{"id":"take-2","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"current":"2","visited":["0","1"],"queue":["2"]},"arrays":[{"name":"indegree","values":[0,0,0,1]},{"name":"order","values":[0,1]}]}},{"id":"take-3","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"visited":["0","1","2","3"],"queue":[]},"arrays":[{"name":"indegree","values":[0,0,0,0]},{"name":"order","values":[0,1,2,3]}]}}]},"beats":[{"id":"take-0","title":"Run task 0. Which of its dependents now reach count 0?","summary":"order is empty and the queue holds only task 0, whose count is 0.","prompt":"Task 0 runs first. Its dependents are tasks 1 and 2.","options":[{"id":"both-released","label":"Both 1 and 2 reach 0 and join the queue; order becomes [0]","rationale":"Tasks 1 and 2 each had exactly one dependency, task 0. Running 0 drops both their counts from 1 to 0, so both are ready and enter the queue. Task 3 is not touched yet because 0 is not one of its dependencies.","isCorrect":true},{"id":"all-three","label":"Tasks 1, 2, and 3 all become ready at once","rationale":"Task 3 depends on 1 and 2, not on 0, so running 0 changes nothing about task 3. Its count stays at 2. Only the direct dependents of 0, which are 1 and 2, drop.","isCorrect":false},{"id":"only-one","label":"Only task 1 becomes ready, since the queue takes one at a time","rationale":"Running 0 lowers the count of every task depending on it in the same round. Both 1 and 2 hit 0 together and both join the queue.","isCorrect":false}],"answer":"Both 1 and 2 drop from 1 to 0 and join the queue, and order becomes [0]. Task 3, which depends on 1 and 2 rather than 0, is untouched and stays at count 2."},{"id":"take-1","title":"Run task 1. Does task 3 become ready now?","summary":"The queue is [1, 2]; task 1 comes off next and its only dependent is task 3.","prompt":"Task 1 runs. Task 3 currently has a remaining count of 2.","options":[{"id":"not-yet","label":"No: task 3 drops from 2 to 1, still waiting on task 2","rationale":"Task 3 needed both 1 and 2. Running 1 removes one of those, so its count falls from 2 to 1, not to 0. It stays out of the queue because task 2 is still ahead of it.","isCorrect":true},{"id":"released-now","label":"Yes: task 3 reaches 0 the moment task 1 runs","rationale":"That would release task 3 after only one of its two dependencies. Its count goes 2 to 1 here, not to 0, so it is not ready, and the queue should not hold it yet.","isCorrect":false},{"id":"unchanged","label":"No change: task 3 is not a dependent of task 1","rationale":"Task 3 does depend on task 1, so running 1 must lower its count. It drops from 2 to 1; the point is that one decrement is not enough to release it.","isCorrect":false}],"answer":"No. Task 3 drops from 2 to 1 and keeps waiting, because task 2 has not run yet. order is now [0, 1]. A task is released only when its count reaches 0, not on the first dependency cleared."},{"id":"take-2","title":"Run task 2. What happens to task 3 this time?","summary":"The queue is [2]; task 2 comes off, and task 3 sits at a count of 1.","prompt":"Task 2 runs. Task 3 already lost its dependency on task 1.","options":[{"id":"released","label":"Task 3 drops from 1 to 0 and finally joins the queue","rationale":"This is task 3's last remaining dependency. Running 2 drops its count from 1 to 0, so now every dependency is cleared and task 3 is ready. It enters the queue.","isCorrect":true},{"id":"still-waiting","label":"Task 3 stays blocked until something resets its count","rationale":"Nothing resets the count; it only ever decreases. Task 2 was the second of task 3's two dependencies, so this decrement takes it to 0 and releases it.","isCorrect":false},{"id":"double-add","label":"Task 3 was already queued when task 1 ran, so it is added twice","rationale":"Task 3 was never queued before: its count was still 1 after task 1. It reaches 0 only now, so this is the first and only time it joins the queue.","isCorrect":false}],"answer":"Task 3 drops from 1 to 0 and joins the queue. order is [0, 1, 2]. Holding the count until both dependencies cleared is what enqueues task 3 exactly once, at the right moment."},{"id":"take-3","title":"The queue is empty. What final check decides what to return?","summary":"Task 3 runs last and the queue is empty.","prompt":"Nothing is left to run, and the walk has to decide whether the order it built is complete.","options":[{"id":"count-matches","label":"Return order only if its length equals numTasks","rationale":"Comparing the number of tasks run against numTasks is the check that separates success from a cycle. Here order holds 4 tasks and numTasks is 4, so every task became runnable and the order is valid. If a task had stayed stuck, order would be shorter and the check would fail.","isCorrect":true},{"id":"queue-empty","label":"Return order as soon as the queue is empty, with no further check","rationale":"The queue also empties when a cycle leaves some tasks stuck forever and they never reach count 0. An empty queue alone proves nothing about how many tasks ran, so this would return a partial order on a cyclic input.","isCorrect":false},{"id":"no-cycle-edges","label":"Scan the dependencies for a back edge and return order if none is found","rationale":"The walk never scans for back edges directly. It detects a cycle by counting: if order is shorter than numTasks, some task never became runnable, and that is far cheaper than searching the edges for a cycle.","isCorrect":false}],"answer":"Compare order's length against numTasks. Here both are 4, so every task was reachable through its dependencies and the order [0, 1, 2, 3] is valid. A shorter order would have meant some task stayed stuck, which is how a cycle shows up."}]},{"id":"direction-pitfall","kind":"pitfall","chapter":"Build it","eyebrow":"Spot the trap","title":"Does it matter which way you point each dependency edge?","workspacePanel":"trace","summary":"A pair [before, after] could be stored as before unlocks after, or the reverse, and both feel like just recording the link. Pointing the arrow from after back to before still counts an indegree and still empties the queue. Watch the order it hands back on a plain chain 0 then 1 then 2.","pitfall":"The code below points each edge backwards: for a pair [before, after] it builds the edge from after to before and counts indegree on before, instead of from before to the after that waits on it.","whyItMatters":"On numTasks = 3 with dependencies = [[0,1],[1,2]], task 0 must run before 1 and 1 before 2, so the only valid order is [0, 1, 2]. Pointing each edge the wrong way makes task 2 look dependency-free and task 0 look blocked, so the walk releases 2 first and returns [2, 1, 0]. It is a full ordering of all three tasks, so the length check passes and the cycle test sees nothing wrong, yet every dependency runs in reverse. Build the edge from before to the task that waits on it, graph[before].append(after), and count indegree on after, so a task runs only after the tasks it depends on.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"graph = [[] for _ in range(numTasks)]\nindegree = [0] * numTasks\nfor before, after in dependencies:\n    graph[after].append(before)\n    indegree[before] += 1\nqueue = [t for t in range(numTasks) if indegree[t] == 0]\norder = []\nwhile queue:\n    task = queue.pop(0)\n    order.append(task)\n    for nxt in graph[task]:\n        indegree[nxt] -= 1\n        if indegree[nxt] == 0:\n            queue.append(nxt)\nreturn order","steps":[{"id":"p-build","title":"Each edge is pointed from after back to before","codeLine":4,"summary":"For pair [0, 1] the arrow goes 1 to 0, and for [1, 2] it goes 2 to 1. indegree counts the before side, giving [1, 1, 0]: task 0 looks blocked and task 2 looks free.","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"}],"edges":[[1,0],[2,1]],"queue":["2"]},"arrays":[{"name":"indegree","values":[1,1,0]}]}},{"id":"p-take-2","title":"Task 2 runs first, before anything it depends on","codeLine":9,"summary":"indegree is [1, 1, 0], so only task 2 seeds the queue. It comes off first and order becomes [2], even though task 2 truly needs 0 and 1 ahead of it.","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"}],"edges":[[1,0],[2,1]],"current":"2","highlighted":["1"],"visited":["2"],"queue":["1"],"activeEdges":[[2,1]]}}},{"id":"p-take-1","title":"Task 1 follows, releasing task 0 last","codeLine":12,"summary":"Running task 2 drops task 1 to 0, then running task 1 drops task 0 to 0. order grows to [2, 1] and task 0 is the last one queued.","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"}],"edges":[[1,0],[2,1]],"current":"1","highlighted":["0"],"visited":["2","1"],"queue":["0"],"activeEdges":[[1,0]]}}},{"id":"p-wrong","title":"Returned [2, 1, 0], the exact reverse of a valid order","codeLine":15,"summary":"All three tasks ran, so the length check passes and no cycle is reported. But the order is [2, 1, 0]: task 2 sits before the 0 and 1 it depends on, so every dependency is violated even though the answer looks complete.","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"}],"edges":[[1,0],[2,1]],"current":"0","visited":["2","1","0"],"queue":[]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const graph = Array.from({ length: numTasks }, () => []);\nconst indegree = Array(numTasks).fill(0);\nfor (const [before, after] of dependencies) {\n    graph[after].push(before);\n    indegree[before] = (indegree[before] + 1);\n}\nconst queue = Array.from({ length: numTasks }, (_, index) => index).filter((t) => indegree[t] === 0);\nconst order = [];\nwhile (queue.length > 0) {\n    const task = queue.shift();\n    order.push(task);\n    for (const nxt of graph[task]) {\n        indegree[nxt] = (indegree[nxt] - 1);\n        if (indegree[nxt] === 0) {\n            queue.push(nxt);\n        }\n    }\n}\nreturn order;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":19},"statementBundles":{"5":{"startLine":5,"endLine":6},"14":{"startLine":15,"endLine":18}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const graph: Array<Array<number>> = Array.from({ length: numTasks }, () => []);\nconst indegree = Array(numTasks).fill(0);\nfor (const [before, after] of dependencies) {\n    graph[after].push(before);\n    indegree[before] = (indegree[before] + 1);\n}\nconst queue = Array.from({ length: numTasks }, (_, index) => index).filter((t) => indegree[t] === 0);\nconst order: Array<number> = [];\nwhile (queue.length > 0) {\n    const task = queue.shift()!;\n    order.push(task);\n    for (const nxt of graph[task]) {\n        indegree[nxt] = (indegree[nxt] - 1);\n        if (indegree[nxt] === 0) {\n            queue.push(nxt);\n        }\n    }\n}\nreturn order;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":19},"statementBundles":{"5":{"startLine":5,"endLine":6},"14":{"startLine":15,"endLine":18}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> graph = new ArrayList<>();\nfor (int i = 0; i < numTasks; i++) {\n    graph.add(new ArrayList<>());\n}\nint[] indegree = new int[numTasks];\nfor (List<Integer> dependency : dependencies) {\n    int before = dependency.get(0);\n    int after = dependency.get(1);\n    graph.get(after).add(before);\n    indegree[before] = (indegree[before] + 1);\n}\nList<Integer> queue = new ArrayList<>();\nfor (int t = 0; t < numTasks; t++) {\n    if (indegree[t] == 0) {\n        queue.add(t);\n    }\n}\nList<Integer> order = new ArrayList<>();\nwhile (!queue.isEmpty()) {\n    int task = queue.remove(0);\n    order.add(task);\n    for (Integer nxt : graph.get(task)) {\n        indegree[nxt] = (indegree[nxt] - 1);\n        if (indegree[nxt] == 0) {\n            queue.add(nxt);\n        }\n    }\n}\nreturn order;","lineMap":{"1":1,"2":5,"3":6,"4":9,"5":10,"6":12,"7":18,"8":19,"9":20,"10":21,"11":22,"12":23,"13":24,"14":25,"15":29},"statementBundles":{"1":{"startLine":1,"endLine":4},"3":{"startLine":6,"endLine":8},"5":{"startLine":10,"endLine":11},"6":{"startLine":12,"endLine":17},"14":{"startLine":25,"endLine":28}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> graph = Enumerable.Range(0, numTasks).Select(_ => new List<int>()).ToList();\nList<int> indegree = Enumerable.Repeat<int>(0, numTasks).ToList();\nforeach (var item in dependencies) {\n    int before = item[0];\n    int after = item[1];\n    graph[after].Add(before);\n    indegree[before] = indegree[before] + 1;\n}\nQueue<int> queue = new(Enumerable.Range(0, numTasks).Where(t => indegree[t] == 0).Select(t => t).ToList());\nList<int> order = new();\nwhile (queue.Count > 0) {\n    int task = queue.Dequeue();\n    order.Add(task);\n    foreach (int nxt in graph[task]) {\n        indegree[nxt] = indegree[nxt] - 1;\n        if (indegree[nxt] == 0) {\n            queue.Enqueue(nxt);\n        }\n    }\n}\nreturn order;","lineMap":{"1":1,"2":2,"3":3,"4":6,"5":7,"6":9,"7":10,"8":11,"9":12,"10":13,"11":14,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"3":{"startLine":3,"endLine":5},"5":{"startLine":7,"endLine":8},"14":{"startLine":17,"endLine":20}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> graph = vector<vector<int>>(num_tasks, vector<int>{});\nvector<int> indegree = vector<int>(num_tasks, 0);\nfor (vector<int> item : dependencies) {\n    int before = item[0];\n    int after = item[1];\n    graph[after].push_back(before);\n    indegree[before] = (indegree[before] + 1);\n}\ndeque<int> queue;\nfor (int t = 0; t < num_tasks; t++) {\n    if (indegree[t] == 0) {\n        queue.push_back(t);\n    }\n}\nvector<int> order;\nwhile (!queue.empty()) {\n    int task = queue.front();\n    queue.pop_front();\n    order.push_back(task);\n    for (int nxt : graph[task]) {\n        indegree[nxt] = (indegree[nxt] - 1);\n        if (indegree[nxt] == 0) {\n            queue.push_back(nxt);\n        }\n    }\n}\nreturn order;","lineMap":{"1":1,"2":2,"3":3,"4":6,"5":7,"6":9,"7":15,"8":16,"9":17,"10":19,"11":20,"12":21,"13":22,"14":23,"15":27},"statementBundles":{"3":{"startLine":3,"endLine":5},"5":{"startLine":7,"endLine":8},"6":{"startLine":9,"endLine":14},"9":{"startLine":17,"endLine":18},"14":{"startLine":23,"endLine":26}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The remaining-count walk took [0, 1, 2, 3] cleanly, releasing each task only when its count reached 0.","Two inputs are worth running before you code: two tasks that depend on each other, dependencies = [[0,1],[1,0]], and an empty dependency list over three tasks."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"}],"edges":[[0,1],[1,0]]}}}]}},{"id":"cycle-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"numTasks = 2, dependencies = [[0,1],[1,0]]: what does the walk return?","workspacePanel":"visualizer","summary":"Task 0 depends on task 1 and task 1 depends on task 0.","options":[{"id":"empty","label":"An empty list: neither task ever reaches count 0","rationale":"Both counts start at 1 and depend on each other, so the queue is empty from the start and nothing ever runs. order stays empty, which is shorter than numTasks, so the walk reports failure by returning [].","isCorrect":true},{"id":"partial","label":"One task, [0], since you can at least run the first one","rationale":"Task 0 needs task 1 finished first and task 1 needs task 0, so neither ever has count 0. The queue never holds either task, so nothing, not even one, is appended.","isCorrect":false},{"id":"both","label":"Both tasks, [0, 1], picking an order arbitrarily","rationale":"There is no valid order: running either task requires the other first. The mutual dependency means both counts stay at 1 forever, so neither can be appended.","isCorrect":false}],"answer":"An empty list. Both tasks sit at count 1 and block each other, so the queue starts empty and order never grows. Because order is shorter than numTasks, the walk returns [] to signal the cycle.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cycle-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"}],"edges":[[0,1],[1,0]],"highlighted":["0","1"]},"arrays":[{"name":"indegree","values":[1,1]},{"name":"order","values":[]}]}}]}},{"id":"no-deps-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"numTasks = 3, dependencies = []: which tasks start in the queue?","workspacePanel":"visualizer","summary":"numTasks = 3 and the dependency list is empty.","options":[{"id":"all-three","label":"All three tasks, since each has a remaining count of 0","rationale":"With no dependencies every count starts at 0, so the initial scan puts all three tasks in the queue in label order. They run in turn, no decrements ever happen, and order holds [0, 1, 2]: a valid order with no special branch needed.","isCorrect":true},{"id":"just-zero","label":"Only task 0, then the rest unlock as it runs","rationale":"Nothing depends on anything here, so running task 0 releases no one. Tasks 1 and 2 are already at count 0 on their own and belong in the queue from the start.","isCorrect":false},{"id":"none","label":"None, because there are no edges to drive the walk","rationale":"A task with no dependencies is runnable immediately, edges or not. The initial scan seeds the queue from every count-zero task, so all three start ready.","isCorrect":false}],"answer":"All three. Every task starts at count 0, so the initial scan queues them in label order and they run as [0, 1, 2]. The same count-zero rule that seeds the queue handles the no-dependencies case without any extra branch.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-deps-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"}],"edges":[]},"arrays":[{"name":"indegree","values":[0,0,0]}]}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Build the dependency order","workspacePanel":"visualizer","summary":"Release a task only when its remaining count hits 0.","body":["Give every task a remaining-dependency count and an outgoing list of the tasks that depend on it. Seed a queue with every task already at count 0, scanning labels in increasing order, and keep an order list for the result.","Take tasks from the front of the queue one at a time, appending each to the order. For every task that depends on the one just run, lower its count and queue it only when the count reaches 0. At the end, return the order if it holds every task, otherwise return an empty list."],"ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[[0,1],[0,2],[1,3],[2,3]],"queue":["0"]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the dependency order","summary":"Build the graph, seed the queue, release dependents, then check the order length.","workspacePanel":"code","checkpoints":[{"id":"calculate-indegree","title":"Initialize indegrees","description":"Create adjacency and indegree state for every task.","commonMistakes":["Only storing outgoing edges","Making the indegree array too short"],"hint":"Use one adjacency list and one indegree count per task.","semanticSpec":{"intent":"Initialize graph relation state and indegree counters.","doneWhen":"The solution creates adjacency storage and an indegree array sized by numTasks.","shouldFailWhen":"This step should fail if indegree state is missing.","roles":["adjacency","indegree"],"mustProve":["Indegree state is initialized for the task set."],"mustNotAccept":["Only scanning dependencies without persistent counters."],"equivalentVariants":["Use arrays, lists, or maps for adjacency and indegree."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]}},{"id":"populate-graph","title":"Populate graph","description":"Read each dependency edge, add it to adjacency, and increment the dependent task's indegree.","commonMistakes":["Reversing the dependency direction","Forgetting to increment indegree"],"hint":"`before` points to `after`, and `after` gains one prerequisite.","semanticSpec":{"intent":"Build the directed dependency graph and its indegree counts from input edges.","doneWhen":"Every dependency appends an outgoing neighbor and increments that neighbor's indegree.","shouldFailWhen":"This step should fail if edges do not update both adjacency and indegree.","roles":["dependency edge","adjacency","indegree"],"mustProve":["Input edges populate relation buckets and indegree counters."],"mustNotAccept":["Counting edges without storing outgoing neighbors."],"equivalentVariants":["Use a dictionary/list adjacency representation with parallel indegree state."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"populate-graph","readMode":"graph-value-query-v1"}]}},{"id":"initialize-queue","title":"Seed zero-indegree queue","description":"Add every task with no prerequisites to the frontier queue.","commonMistakes":["Starting from only task 0","Adding tasks whose indegree is not zero"],"hint":"Scan all task labels and enqueue those with indegree 0.","semanticSpec":{"intent":"Initialize the Kahn frontier with all currently unlocked tasks.","doneWhen":"The solution scans tasks and enqueues those with zero indegree.","shouldFailWhen":"This step should fail if the frontier is not seeded from indegree values.","roles":["queue","indegree"],"mustProve":["Zero-indegree tasks are added to the work queue."],"mustNotAccept":["Starting from an arbitrary single task."],"equivalentVariants":["Use a list with a head index or a deque."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]}},{"id":"process-queue","title":"Emit task order","description":"Process queued tasks and append each emitted task to the answer order.","commonMistakes":["Processing the queue but never recording the order","Using stack order after choosing FIFO frontier processing"],"hint":"Each popped task becomes the next task in the order.","semanticSpec":{"intent":"Turn the zero-indegree frontier into an output order.","doneWhen":"The loop removes queued tasks and appends them to the result order.","shouldFailWhen":"This step should fail if processed tasks are not recorded.","roles":["queue","order"],"mustProve":["A task taken from the frontier is appended to the result order."],"mustNotAccept":["Returning the queue itself without processing dependencies."],"equivalentVariants":["Use destructive pops or a head index over a list queue."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"records_topological_order","scope":"process-queue","readMode":"graph-value-query-v1"}]}},{"id":"update-neighbors","title":"Unlock neighbors","description":"For each emitted task, decrement its neighbors' indegrees and enqueue newly unlocked tasks.","commonMistakes":["Not decrementing indegree","Enqueuing neighbors before their indegree reaches zero"],"hint":"A neighbor is ready only when all prerequisites have been emitted.","semanticSpec":{"intent":"Advance the topological frontier through outgoing dependency edges.","doneWhen":"The loop decrements neighbor indegrees and enqueues neighbors whose indegree becomes zero.","shouldFailWhen":"This step should fail if neighbors are not unlocked from processed tasks.","roles":["current task","neighbor","indegree","queue"],"mustProve":["Neighbor indegrees are decremented and zero-indegree neighbors are enqueued."],"mustNotAccept":["Appending every neighbor without checking indegree."],"equivalentVariants":["Use any queue representation as long as zero-indegree neighbors reenter the frontier."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"updates_topology_neighbors","scope":"update-neighbors","readMode":"graph-value-query-v1"}]}},{"id":"check-cycle","title":"Check completion","description":"Return the order only if every task was emitted; otherwise return an empty list.","commonMistakes":["Returning a partial order when a cycle exists","Checking dependency count instead of emitted task count"],"hint":"A valid topological order must contain exactly numTasks tasks.","semanticSpec":{"intent":"Use the output length to reject cyclic dependency graphs.","doneWhen":"The method returns the order when its length equals numTasks, otherwise [].","shouldFailWhen":"This step should fail if a partial order can be returned after a cycle.","roles":["order","task count","cycle check"],"mustProve":["The returned order is gated by the number of emitted tasks."],"mustNotAccept":["Returning a partial order without checking completion."],"equivalentVariants":["Compare len(order) with numTasks or track an equivalent completed count."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_topological_order_or_empty","scope":"check-cycle","readMode":"graph-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"A per-task count of remaining dependencies turns \"what is runnable now\" into a single zero check.","body":["Ordering under dependencies comes down to one question asked over and over: which task has nothing left ahead of it? A remaining-dependency count answers it in O(1) per task.","Running a task lowers that count for its dependents, and a task is released the instant its count reaches 0. Touching each task and edge once gives O(V + E), and counting the run tasks against numTasks catches a cycle."],"takeaways":[{"title":"Release only at zero","body":"A task enters the queue only when its remaining count reaches 0, so a task with several dependencies waits for all of them and is queued exactly once."},{"title":"The count is the readiness signal","body":"Holding a remaining-dependency count per task turns \"is this runnable\" into a single comparison, which is what makes the walk a single O(V + E) pass."},{"title":"Short order means a cycle","body":"If the order ends shorter than numTasks, some task never reached count 0, so a cycle blocked it and the answer is an empty list."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"starterFunctionName":"findTaskOrder","tags":["Graph","Topological Sort","Queue"]}
