686. Prerequisite Lookups

A university has n courses numbered 0 to n - 1. Each pair [a, b] in prerequisites means course a must be completed before course b. The pairs never form a loop. A course u is a prerequisite of course v when u must be completed before v, either directly or through a chain of such pairs.

Each entry [u, v] in queries asks whether u is a prerequisite of v. Return a boolean array with one answer per query, in the same order. A course is never a prerequisite of itself, and queries may repeat.

There can be many queries, so compute the reachability information once instead of searching again for every query.

Example 1

Input:
n = 5prerequisites = [[0,2],[2,3],[1,3],[3,4]]queries = [[0,4],[1,2],[4,0],[2,4]]
Output:
[true,false,false,true]
Explanation:

Course 0 leads to 2, 3 and 4, so it is a prerequisite of 4; courses 1 and 2 are unrelated; and prerequisites never point backwards.

Example 2

Input:
n = 2, prerequisites = [], queries = [[0,1]]
Output:
[false]
Explanation:

No pairs exist, so nothing is a prerequisite of anything.

Constraints

2 ≤ n ≤ 2500

0 ≤ prerequisites.length ≤ 10000; the pairs contain no cycle and may repeat

1 ≤ queries.length ≤ 20000; 0 ≤ u, v < n

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(n*m/w + q)
Space
O(n^2/w)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…