Course Schedule IV
Explanation & Solution
Description
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that course ai must be taken before course bi.
Prerequisites can be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.
You are also given an array queries where queries[j] = [uj, vj]. For each query, answer whether course uj is a prerequisite of course vj (either directly or indirectly).
Return a boolean array answer where answer[j] is the answer to the j-th query.
Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
Explanation: Course 1 is a prerequisite of course 0. Course 0 is not a prerequisite of course 1.
Constraints
2 <= numCourses <= 1000 <= prerequisites.length <= (numCourses * (numCourses - 1)) / 2prerequisites[i].length == 20 <= ai, bi <= numCourses - 1ai !== bi- All pairs
[ai, bi]are unique - The prerequisites graph has no cycles
1 <= queries.length <= 100000 <= uj, vj <= numCourses - 1uj !== vj
Approach
Topological Sort pattern
1. Build the Graph
- Create an adjacency list from the
prerequisitesarray - For each pair
[a, b], add a directed edge fromatob(a is prerequisite of b) - Track the in-degree of each node for topological sorting
2. Initialize Reachability Sets
- Create a
Setfor each course to store all its prerequisites (direct and indirect) - Initially all sets are empty
3. Topological Sort with Reachability Propagation
- Use Kahn's algorithm — start BFS from nodes with in-degree 0
- When processing an edge
curr -> next: - Add
currtoreachable[next](direct prerequisite) - Add all of
reachable[curr]toreachable[next](indirect prerequisites) - Decrement in-degree and add to queue when it reaches 0
- Processing in topological order ensures that when we visit a node, all its prerequisites are already computed
4. Answer Queries
- For each query
[u, v], check ifuis inreachable[v] - If yes,
uis a prerequisite (direct or indirect) ofv - Return the boolean array of answers
Key Insight
- Processing nodes in topological order guarantees that when we propagate reachability from
currtonext,curr's reachability set is already complete - This is essentially computing the transitive closure of the prerequisite graph
- Using Sets makes the lookup for each query O(1)