You are given an integer numCourses representing the courses labeled from 0 to numCourses - 1, together with a list of prerequisites where each pair [a, b] means course a must be taken before course b. A course x is a prerequisite of course y if x appears directly before y, or if x is a prerequisite of some course z that is itself a prerequisite of y. In other words, the prerequisite relation is transitive.
You are also given a list of queries where each query [u, v] asks whether course u is a prerequisite (directly or indirectly) of course v. Return a boolean array whose i-th entry answers the i-th query.
The graph of courses is guaranteed to have no cycles, so a consistent ordering of the courses always exists.
Example 1
Input: numCourses = 3, prerequisites = [[0,1],[1,2]], queries = [[0,2],[2,0]]
Output: [true,false]
0 leads to 1 and 1 leads to 2, so 0 is an indirect prerequisite of 2 (true). There is no path from 2 back to 0, so the second answer is false.
Example 2
Input: numCourses = 2, prerequisites = [], queries = [[0,1],[1,0]]
Output: [false,false]
With no prerequisite edges, neither course can be reached from the other, so both queries are false.
Constraints
2 <= numCourses <= 1000 <= prerequisites.length <= (numCourses * (numCourses - 1)) / 2prerequisites[i].length == 20 <= a, b < numCoursesa != b, and all prerequisite pairs are uniqueThe prerequisite graph is a DAG (no cycles)1 <= queries.length <= 10^4queries[i].length == 20 <= u, v < numCoursesSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI