MediumDepth-First SearchBreadth-First SearchGraphTopological SortMatrix

Course Schedule IV

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now