The one-prerequisite constraint is a gift if you notice it early.
Model the courses as a directed graph where edges represent prerequisites, then perform a topological sort. Since each course has at most one direct prerequisite, the graph is a collection of chains and trees, allowing for a simpler traversal or even a direct mapping approach.
Pro tip: Clarify with the interviewer whether the input is guaranteed to be a valid DAG (no cycles). If cycles are possible, you must detect and handle them; otherwise, you can assume a solution exists and focus on efficiency.
Restate the problem: given n courses and prerequisite pairs (b before a), return any valid order. Note the constraint: each course has at most one direct prerequisite, which simplifies the graph structure.
Represent the graph using an adjacency list for prerequisites (b -> a) and an array to track in-degrees or a map from course to its prerequisite. Since each course has at most one prerequisite, you can also use a parent array.
Use topological sort: either Kahn's algorithm (BFS with in-degree tracking) or DFS with cycle detection. Given the constraint, you can also process chains directly by following prerequisites.
Write code to compute the order. Handle cases like no prerequisites, multiple disconnected components, and possible cycles (if not guaranteed acyclic). Return any valid order.
State time and space complexity (O(n + m) for graph traversal). Walk through a small example to verify correctness, including edge cases.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.