← All problems

1462. Course Schedule IV

MediumOpen on LeetCodeProblem statement

Problem Statement

1462. Course Schedule IV

Medium


There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.

Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.

You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.

Return a boolean array answer, where answer[j] is the answer to the jth query.

 

Example 1:

Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
Output: [false,true]
Explanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.

Example 2:

Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]
Output: [false,false]
Explanation: There are no prerequisites, and each course is independent.

Example 3:

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

 

Constraints:

Java

Source file
class Solution {
    public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
        Set<Integer>[] adj = new Set[numCourses];
        boolean[] vis = new boolean[numCourses];
        for (int i = 0; i < numCourses; i++)
            adj[i] = new HashSet<>();
        for (int[] p : prerequisites)
            adj[p[1]].add(p[0]);
        for (int i = 0; i < numCourses; i++)
            dfs(adj, i, vis);
        System.out.println(Arrays.toString(adj));
        List<Boolean> ans = new ArrayList<>();
        for (int[] q : queries)
            ans.add(adj[q[1]].contains(q[0]));
        return ans;
    }

    private Set<Integer> dfs(Set<Integer>[] adj, int i, boolean[] vis) {
        if (vis[i])
            return adj[i];
        vis[i] = true;
        Set<Integer> finalPreReqList = new HashSet<>(adj[i]);
        for (int preReq : adj[i])
            finalPreReqList.addAll(dfs(adj, preReq, vis));
        return adj[i] = finalPreReqList;
    }
}