Course Schedule IV
Answer whether one course is a direct or indirect prerequisite of another.
Open on LeetCode ↗Intuition
Running a fresh graph search for every query repeats the same reachability work. The prerequisite graph is a DAG, so each course's complete prerequisite set can be propagated in topological order. When a course becomes ready, all information from its predecessors is already known. Unioning those sets with the direct predecessor answers every later query in constant average lookup time.
Many reachability queries over one fixed DAG justify precomputing transitive closure. Topological propagation is especially natural when each node's answer can be assembled from its predecessors' answers.
Approach
Orient edges from prerequisite to dependent course
For pair [a, b], add a -> b and increase b's indegree. Maintain a set for every course that will contain all courses required before it.
Propagate prerequisite ancestry topologically
Start with zero-indegree courses. For every edge course -> next, add course and everything required by course into next's set before decreasing its indegree.
Answer from the completed closure
After all courses are processed, query [u, v] is true exactly when u belongs to the prerequisite set of v. This includes paths of any positive length but never treats a course as its own prerequisite.
Solution
Common pitfalls
Reversing the prerequisite edge
graph[b].append(a)
graph[a].append(b)
The pair states that course a must come before course b.
Propagating ancestors but omitting the direct course
required[next].update(required[course])
required[next].update(required[course]) required[next].add(course)
The direct predecessor is a prerequisite even if it has no ancestors.
Checking the wrong set
v in required[u]
u in required[v]
The set belongs to the dependent course and contains what must precede it.
Edge cases
The predecessor itself is inserted into the dependent course's set.
Set propagation carries every earlier ancestor through the chain.
No propagation connects their sets, so the query is false.