Knew immediately it was topological sort, which felt reassuring.
Model the courses and prerequisites as a directed graph and perform a topological sort using Kahn's algorithm (BFS with in-degree tracking). If the topological order contains all n courses, return it; otherwise, a cycle exists and return an empty array.
Pro tip: Explicitly mention that you're using Kahn's algorithm because it naturally detects cycles by checking if the processed count equals n, and it's iterative, avoiding recursion depth issues. Also, clarify that the problem guarantees a unique solution only if the graph is a DAG, so any valid topological order is acceptable.
Confirm that the input is a list of prerequisite pairs and that we need any valid ordering. Build a directed graph where an edge from b to a indicates b must come before a, and compute in-degrees for each node.
Create an adjacency list for the graph, an array to store in-degrees, and a queue for nodes with in-degree 0. Also prepare a result list to store the topological order.
Enqueue all nodes with in-degree 0. While the queue is not empty, dequeue a node, add it to the result, and for each neighbor, decrement its in-degree; if it becomes 0, enqueue it.
After processing, if the result contains all n courses, return it; otherwise, a cycle exists, so return an empty array.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.