Course Schedule IV
The key idea
a leads to b and b leads to c, then a leads to c. Precompute the full reachability (transitive closure) of the directed graph once, then every query is an O(1) table lookup.Problem
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] = [a, b] indicates that you must take course a first if you want to take course b.
For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.
Prerequisites can also 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] = [u, v]. For the j-th query, you should answer whether course u is a prerequisite of course v or not.
Return a boolean array answer, where answer[j] is the answer to the j-th query.
Constraints
2 <= n <= 1000 <= prerequisites.length <= (n * (n - 1) / 2)0 <= prerequisites[i][0], prerequisites[i][1] < nprerequisites[i][0] != prerequisites[i][1]- The prerequisites graph has no cycles or repeated edges.
1 <= queries.length <= 10^4queries[i][0] != queries[i][1]
Examples
Complexity
Time: O(n^3 + q) Space: O(n^2)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Graph problems
- Cheapest Flights Within K StopsMEDIUM
- Clone GraphMEDIUM
- Evaluate DivisionMEDIUM
- Find the Town JudgeEASY
- Min Cost to Connect All PointsMEDIUM
- Minimum Height TreesMEDIUM
- Network Delay TimeMEDIUM
- Number of ProvincesMEDIUM
- Path With Minimum EffortMEDIUM
- Reconstruct ItineraryHARD
- Swim in Rising WaterHARD