Problem Description
Determine if a course is a prerequisite for another given a list of courses and their direct prerequisites. Prerequisites can be indirect; that is, if course A is required for B and B is required for C, then A is required for C. For each query, answer whether one course is a prerequisite for another.
Key Insights
- Represent courses and prerequisites as a directed acyclic graph (DAG).
- Use graph traversal techniques (DFS or BFS) or compute the transitive closure.
- The Floyd Warshall algorithm can precompute reachability between all courses.
- After precomputation, each query can be answered in constant time by checking the reachability matrix.
Space and Time Complexity
Time Complexity: O(N^3 + Q) where N = numCourses (Floyd Warshall algorithm) and Q = number of queries
Space Complexity: O(N^2) for storing the reachability matrix
Solution
We solve the problem by converting it into computing reachability in a DAG. The approach is to use the Floyd Warshall algorithm to compute a transitive closure.
Steps:
- Build a boolean reachability matrix and mark direct prerequisites.
- Use a triple-nested loop (Floyd Warshall) to update the matrix such that if course i can reach course k and course k can reach course j, then course i can reach course j.
- Answer each query in constant time by checking the precomputed reachability matrix.