This is basically topological sort dressed up as a scheduling problem.
Start by restating the problem as a topological sort on a directed graph, then present Kahn's algorithm (BFS-based) as your primary solution, clearly explaining how in-degree tracking and queue processing naturally detect cycles. Alternatively, mention DFS with recursion stack for cycle detection, and compare trade-offs between the two approaches.
Pro tip: Emphasize that Kahn's algorithm is often preferred in interviews because it detects cycles without extra state and produces a valid ordering in one pass; also note that if multiple valid orderings exist, any topological order is acceptable unless a specific tie-breaking rule is given.
Explain that tasks are nodes and prerequisite pairs (a, b) become directed edges b → a, since b must come before a. Clarify that a valid ordering is a topological sort, and a cycle means no such ordering exists.
Present Kahn's algorithm: compute in-degrees for all nodes, use a queue to process nodes with in-degree 0, and build the ordering. Mention adjacency list representation for O(V+E) space and time.
Detail: initialize in-degree array, enqueue all zero in-degree nodes, repeatedly dequeue a node, append to result, decrement in-degrees of its neighbors, and enqueue any that become zero. After processing, if result length < n, a cycle exists.
State time complexity O(V+E) and space O(V+E). Explain that cycle detection is inherent: if the queue empties before all nodes are processed, the remaining nodes form at least one cycle.
Note that any topological order is valid; if a specific order is required (e.g., lexicographically smallest), use a min-heap instead of a queue. Discuss edge cases: no prerequisites, disconnected components, and self-loops.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.