This is basically two problems stapled together and I didn't see that fast enough.
Model the prerequisites as a directed graph and use topological sorting (Kahn's algorithm) to detect cycles and produce a valid ordering. First validate that all referenced courses exist, collecting any missing ones. Then attempt topological sort; if it fails, extract a cycle from the remaining nodes.
Pro tip: Explicitly discuss how you would extract a cycle when a cycle is detected, and mention that Kahn's algorithm naturally leaves the cyclic nodes in the queue, making it easy to identify a cycle. Also, clarify that the ordering is not unique and any valid topological order is acceptable.
Confirm that course IDs are unique, prerequisites are directed edges, and that missing courses should be reported. Discuss handling of empty inputs, self-loops, and duplicate edges.
Iterate through all prerequisite pairs and check if both u and v exist in the course set. Collect any missing course IDs into a list to return if invalid.
Construct an adjacency list for the directed graph and compute the in-degree for each course. This prepares for topological sorting.
Use Kahn's algorithm: enqueue nodes with in-degree 0, repeatedly dequeue and reduce in-degrees of neighbors. If the sorted list contains all courses, return true and the ordering; otherwise, a cycle exists.
If a cycle is detected, perform a DFS on the remaining nodes (those with in-degree > 0) to find and return one cycle. Combine missing courses and cycle in the invalid response.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.