Course Schedule IV (LeetCode 1462): Solution and Explanation
Given a prerequisite graph with no cycles and a list of queries [u, v], answer for each query whether course u must be taken, directly or through a chain, before course v.
Intuition
A query asks whether there is a path from u to v. There can be ten thousand queries but only 100 courses, so it pays to compute the answer for every pair once and then look queries up.
If you visit courses in topological order, a course is only processed after all of its direct prerequisites. Each of those already knows its full prerequisite set, so the course can build its own set by merging theirs.
Kahn's algorithm gives that order for free: a course enters the queue when its last incoming arrow is processed, which is exactly when its set is complete.
Approach: Kahn's topological sort with a reachability matrix
- Build adjacency lists from the prerequisite pairs and count each course's in-degree.
- Create an n x n boolean matrix
reach, wherereach[v][k]means k is a prerequisite of v. - Put every course with in-degree 0 in a queue.
- Pop a course u. For each arrow u -> v, set
reach[v][u]and copy every true entry of row u into row v. Decrease v's in-degree and enqueue it when it reaches 0. - Answer each query [u, v] with
reach[v][u].
Step-by-step example
numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
- The arrow is 1 -> 0. In-degrees: course 0 has 1, course 1 has 0.
- The queue starts with course 1, whose prerequisite set is empty.
- Pop 1. Along 1 -> 0, course 0 gains 1, so its set becomes {1}. Its in-degree drops to 0 and it is enqueued.
- Pop 0. It has no outgoing arrows.
- Query [0,1]: is 0 in the set of 1? No, false. Query [1,0]: is 1 in the set of 0? Yes, true. Return [false,true].
Code: Python, Java, C++
1class Solution:
2 def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
3 adj = [[] for _ in range(numCourses)]
4 indeg = [0] * numCourses
5 for a, b in prerequisites:
6 adj[a].append(b)
7 indeg[b] += 1
8 reach = [[False] * numCourses for _ in range(numCourses)]
9 queue = deque(i for i in range(numCourses) if indeg[i] == 0)
10 while queue:
11 u = queue.popleft()
12 for v in adj[u]:
13 reach[v][u] = True
14 for k in range(numCourses):
15 if reach[u][k]:
16 reach[v][k] = True
17 indeg[v] -= 1
18 if indeg[v] == 0:
19 queue.append(v)
20 return [reach[v][u] for u, v in queries]1class Solution {
2 public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
3 List<List<Integer>> adj = new ArrayList<>();
4 for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());
5 int[] indeg = new int[numCourses];
6 for (int[] p : prerequisites) {
7 adj.get(p[0]).add(p[1]);
8 indeg[p[1]]++;
9 }
10 boolean[][] reach = new boolean[numCourses][numCourses];
11 Deque<Integer> queue = new ArrayDeque<>();
12 for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) queue.offer(i);
13 while (!queue.isEmpty()) {
14 int u = queue.poll();
15 for (int v : adj.get(u)) {
16 reach[v][u] = true;
17 for (int k = 0; k < numCourses; k++) {
18 if (reach[u][k]) reach[v][k] = true;
19 }
20 if (--indeg[v] == 0) queue.offer(v);
21 }
22 }
23 List<Boolean> result = new ArrayList<>();
24 for (int[] q : queries) result.add(reach[q[1]][q[0]]);
25 return result;
26 }
27}1class Solution {
2public:
3 vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
4 vector<vector<int>> adj(numCourses);
5 vector<int> indeg(numCourses, 0);
6 for (auto& p : prerequisites) {
7 adj[p[0]].push_back(p[1]);
8 indeg[p[1]]++;
9 }
10 vector<vector<bool>> reach(numCourses, vector<bool>(numCourses, false));
11 queue<int> q;
12 for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) q.push(i);
13 while (!q.empty()) {
14 int u = q.front();
15 q.pop();
16 for (int v : adj[u]) {
17 reach[v][u] = true;
18 for (int k = 0; k < numCourses; k++) {
19 if (reach[u][k]) reach[v][k] = true;
20 }
21 if (--indeg[v] == 0) q.push(v);
22 }
23 }
24 vector<bool> result;
25 for (auto& qu : queries) result.push_back(reach[qu[1]][qu[0]]);
26 return result;
27 }
28};Time and space complexity
O(n * (n + m) + q)
Each of the m arrows copies one row of n booleans, the sweep touches every course once, and each of the q queries is a single lookup.
O(n^2 + m)
The reachability matrix has n^2 entries and the adjacency lists hold the m arrows.
Other approaches
Floyd-Warshall transitive closure (time O(n^3 + q), space O(n^2))
Start with reach[a][b] = true for each pair and, for every middle course k, set reach[i][j] when reach[i][k] and reach[k][j]. Three nested loops, very short to write.
DFS from every course (time O(n * (n + m) + q), space O(n^2))
From each course run a DFS along the arrows and mark everything it reaches. With n DFS runs this is also a full transitive closure.
Search per query (time O(q * (n + m)), space O(n + m))
Run a BFS from u for each query and stop when v is found. Fine for a handful of queries, too slow when there are thousands.
Common mistakes
- Reading the pair backwards. [a, b] means a comes before b, and a query [u, v] asks whether u comes before v, so the lookup is reach[v][u] when rows hold prerequisites.
- Only checking direct arrows. Prerequisites are transitive, so a course two or more steps back still counts.
- Merging a course's set before that course is final. Without a topological order, a set can be copied while it is still missing members.
- Running a fresh search for every query. With up to ten thousand queries that repeats a lot of work.
Frequently asked questions
Why does processing in topological order guarantee complete sets?
A course enters the queue only after every arrow into it has been processed, and each of those arrows came from a course that was itself already complete. By induction, every popped course has its full prerequisite set.
Is Floyd-Warshall good enough here?
Yes. With at most 100 courses, n^3 is one million steps, which is fast. The topological version does less work on sparse graphs.
What if a query names two courses with no connection?
Neither set contains the other, so both directions answer false.
Could I use bitsets for the sets?
Yes. Storing each row as a bitmask turns the row copy into one OR operation, which speeds up the merge by a large constant factor.