Course Schedule IV

Given numCourses, prerequisite pairs, and queries, return for each query whether the first course is a prerequisite of the second course. Pattern focus: Indegree. A topological order combined with reachability propagation solves this cleanly.

Input Format

numCourses = course count, prerequisites = prerequisite pairs, queries = prerequisite checks

Output Format

boolean array indicating whether each query is true

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9

Examples

Example 1:

Input:

numCourses = 2
prerequisites = [[1,0]]
queries = [[0,1],[1,0]]

Output:

[false,true]

Explanation:

Course 0 is a prerequisite of 1, but not the other way around.

Example 2:

Input:

numCourses = 3
prerequisites = [[1,0],[2,1]]
queries = [[0,2],[0,1],[1,2]]

Output:

[false,false,false]

Explanation:

The chain 0 -> 1 -> 2 makes all three queries true.

Example 3:

Input:

numCourses = 3
prerequisites = [[0,1]]
queries = [[0,1],[1,2]]

Output:

[true,false]

Explanation:

Without dependencies, no course is a prerequisite of another.

Loading...
Course Schedule IV - Topological Sort