I started with Kahn's algorithm and felt pretty good about it, but the tie-breaking requirement tripped me up for a few minutes.
Use Kahn's algorithm (BFS-based topological sort) with a min-heap or sorted list to break ties by the order nodes first appear as sources. First, build the graph and compute in-degrees while recording the first-seen order of source nodes. Then repeatedly extract the available node with the smallest first-seen index, append it to the result, and decrement in-degrees of its neighbors.
Pro tip: Clarify edge cases upfront—such as cycles, duplicate edges, or nodes that appear only as destinations—and mention that the tie-breaking rule is a stable ordering constraint that can be implemented with a priority queue keyed by first-seen index. This shows you think about robustness and real-world data quality.
Iterate through the edge list to build an adjacency list and compute in-degrees for each node. Also record the first-seen order of each node when it appears as a source (the first element of an edge).
Collect all nodes with in-degree zero into a priority queue (or sorted list) ordered by their first-seen index. If a node never appears as a source, assign it a default order (e.g., infinity) or handle it as needed.
While the priority queue is not empty, extract the node with the smallest first-seen index, add it to the topological order, and for each neighbor, decrement its in-degree. If a neighbor's in-degree becomes zero, insert it into the priority queue.
After processing, if the topological order does not contain all nodes, a cycle exists. Return an error or empty list as appropriate. Otherwise, return the valid ordering.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.