oneby7

Graphs Topological sort

460. Course Schedule IV

Medium

There are numCourses courses, numbered from 0 to numCourses - 1. Each pair [a, b] in prerequisites means you must take course a before course b.

Prerequisites carry over. If a comes before b and b comes before c, then a is also a prerequisite of c, even though no pair says so. The pairs never form a cycle.

Each query [u, v] in queries asks whether course u is a prerequisite of course v, directly or through other courses. Return a list with one answer per query, true or false, in the order of the queries.

Example 1

01234

Input: numCourses = 5 prerequisites = [[0, 1], [1, 2], [3, 2], [2, 4]] queries = [[0, 4], [3, 1], [4, 0], [3, 4]]

Output: [true,false,false,true]

Explanation: Course 0 comes before 1, 1 before 2, and 2 before 4, so 0 is a prerequisite of 4. Course 3 comes before 2 and so before 4, but nothing links it to 1. Course 4 comes after 0, not before it.

Example 2

012

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

Output: [false,false,false]

Explanation: With no pairs, no course is a prerequisite of another, in either direction.

Example 3

0123

Input: numCourses = 4 prerequisites = [[3, 2], [2, 1], [1, 0]] queries = [[0, 3], [3, 0], [2, 0]]

Output: [false,true,true]

Explanation: The pairs form one chain, 3 → 2 → 1 → 0. So 3 and 2 are both prerequisites of 0, and 0 is a prerequisite of nothing.

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • 2 ≤ numCourses ≤ 1000
  • 0 ≤ prerequisites.length ≤ 105
  • prerequisites[i].length == 2
  • 0 ≤ ai, bi < numCourses
  • ai ≠ bi
  • No pair appears twice.
  • The pairs form no cycle.
  • 1 ≤ queries.length ≤ 105
  • queries[j].length == 2
  • 0 ≤ uj, vj < numCourses
  • uj ≠ vj

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.