Learning pathsPricingChecking sign-in…
Trees, graphs and optimization

Topological sort

Order work constrained by dependencies.

Directed constraints admit a full completion order exactly when no directed cycle blocks them.

Mechanism and state

Orient each prerequisite pair as prerequisite→course. Count every incoming edge, including duplicate entries if they are permitted. Start with every zero-indegree vertex, including isolated IDs. Finishing a ready vertex removes its outgoing edges; an indegree transition to zero makes a dependent ready.

Why the pattern works

Indegrees always count edges from unfinished prerequisites. A dequeued course is safe to finish. Any nonempty DAG has a zero-indegree vertex, so a stuck remainder contains a cycle. A cycle cannot release its first member, so processing fewer than V vertices proves infeasibility.

Work through an example

For three courses and duplicate pairs [[1,0],[1,0]], initial indegrees are [0,2,0]. Finish 0 and remove both edges; course 1 becomes ready. Isolated course 2 also counts toward the total.

Where the reasoning fails

Deduplicating adjacency while counting duplicate indegrees leaves false unmet edges. A valid order is often nonunique, so tests should check edge ordering rather than equality with one arbitrary sequence. A boolean feasibility result is not an actual cycle witness.

Reconstruct the reasoning

Add a disconnected cycle alongside an isolated course and trace why processing some vertices does not prove all courses can finish.

Apply this foundation

Your study notes