AAlgoLoopSpaced repetition for LeetCode
MEDIUMGraphLeetCode ↗

Course Schedule IV

The key idea

Prerequisites are transitive: if 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

Examples

Input: n = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]] Output: [false,true]
Input: n = 2, prerequisites = [], queries = [[1,0],[0,1]] Output: [false,false]
Input: n = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]] Output: [true,true]

Complexity

Time: O(n^3 + q) Space: O(n^2)

See the full solution

410310
Step-by-step visualization
Start free →

More Graph problems