MediumDepth-First SearchBreadth-First SearchGraphTopological SortMatrix

1 approach, code in every language

Problem description

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 <= 100
  • 0 <= prerequisites.length <= (numCourses * (numCourses - 1)) / 2
  • prerequisites[i].length == 2
  • 0 <= a, b < numCourses
  • a != b, and all prerequisite pairs are unique
  • The prerequisite graph is a DAG (no cycles)
  • 1 <= queries.length <= 10^4
  • queries[i].length == 2
  • 0 <= u, v < numCourses

After the pattern

Now solve one you haven't seen.

Which Modules Must Come First is our own problem on the technique behind Course Schedule IV: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free