Problem overview
The method canFinish(int numCourses, int[][] prerequisites) receives the number of courses, labeled 0 to numCourses - 1, and a list of pairs. A pair [a, b] means course b must be taken before course a. The method returns true if all the courses can be finished and false otherwise.
With numCourses = 2 and prerequisites = [[1, 0]], course 0 needs nothing and course 1 needs course 0, so the order 0, 1 works and the answer is true. With [[1, 0], [0, 1]] each course waits for the other, so neither can ever start and the answer is false.
Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that needs it. All the courses can be finished exactly when there is an order of all of them in which every arrow points forward (a topological order). Such an order exists exactly when the arrows contain no cycle.
Approach: keep taking courses that are free
A course is free when all of its prerequisites have been taken. Start with the courses that have no prerequisites at all. Taking one removes its outgoing arrows, which may free other courses. Repeat until nothing is free. If every course was taken, the answer is true. If some were left, each of them is waiting for another one that is also left, so there is a cycle, and the answer is false.
This is Kahn's algorithm. It needs two pieces of data:
- for every course
b, the list of courses that wait for it (graph.get(b)); - for every course
a, its in-degree: the number of prerequisites still not taken, which is the number of arrows pointing intoa.
A queue holds the free courses. Each course enters it at most once, because its count reaches 0 only once, and each pair is looked at once when its first course is taken. That makes the work O(V + E) for V courses and E pairs.
Step by step
- Create
graphas aList<List<Integer>>backed by anArrayList. - Add one empty inner list per course in a loop. Java has no one-line way to make a list of separate lists, so they are added one by one.
- Create
inDegree, anintarray of sizenumCourses, filled with zeros. - Turn each pair into an arrow. For a pair
prereq, addprereq[0]tograph.get(prereq[1]), because courseprereq[1]comes first andprereq[0]waits for it. Then add 1 toinDegree[prereq[0]], since it has one more prerequisite. - Create
queueas anArrayDequedeclared asDeque<Integer>.addputs a course at the back andpollremoves the one at the front, both in constant time. - Seed the queue with every course whose
inDegreeis 0. - Count the taken courses in
taken, starting at 0. - Loop while the queue isn't empty. Poll a course, add 1 to
taken, and visit every course in its list. - Release the waiting courses. Subtract 1 from each one's
inDegree. If it reaches 0, its last prerequisite was just taken, so add it to the queue. - Return
taken == numCourses.
The solution in Java
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<>());
}
int[] inDegree = new int[numCourses];
for (int[] prereq : prerequisites) {
graph.get(prereq[1]).add(prereq[0]);
inDegree[prereq[0]]++;
}
Deque<Integer> queue = new ArrayDeque<>();
for (int course = 0; course < numCourses; course++) {
if (inDegree[course] == 0) {
queue.add(course);
}
}
int taken = 0;
while (!queue.isEmpty()) {
int course = queue.poll();
taken++;
for (int nextCourse : graph.get(course)) {
inDegree[nextCourse]--;
if (inDegree[nextCourse] == 0) {
queue.add(nextCourse);
}
}
}
return taken == numCourses;
}
}
The Java details worth a closer look:
- Declare with the interface.
ListandDequeare interfaces andArrayListandArrayDequeare the classes behind them. The diamond<>lets the compiler infer the type arguments. - Autoboxing.
queue.poll()returns anInteger, which is unboxed to anintautomatically. The enhancedforovergraph.get(course)unboxes each element the same way.pollreturnsnullon an empty queue, but the loop condition guarantees the queue isn't empty, so unboxing never fails here. - Arrays start at zero.
new int[numCourses]is all zeros, which is the right starting count before the pairs are read. - Direction matters. For
[a, b]the list belongs tob(prereq[1]) and the counter toa(prereq[0]). Mixing the two up reverses every arrow, and the queue then no longer yields courses in a valid order to take them. - Imports. A complete file using these types needs
import java.util.*;.
Complexity
Time: O(V + E). Building the lists and counts touches every course and every pair once. Each course enters and leaves the queue at most once, and the inner loop runs once per pair across the whole run.
Space: O(V + E). The adjacency lists hold one entry per pair, and inDegree and the queue hold at most one entry per course.
Edge cases and common mistakes
- No prerequisites. Every count is 0, every course goes into the queue at the start, and
takenends atnumCourses. With 3 courses and no pairs the answer istrue. - A cycle. For
[[1, 0], [0, 1]]no course starts with a count of 0, so the queue is empty from the beginning,takenstays 0 and the method returnsfalse. - A cycle with free courses around it. With 3 courses and
[[1, 0], [2, 1], [1, 2]], course 0 is taken, but courses 1 and 2 wait for each other, sotakenis 1 and the answer isfalse. Courses outside a cycle can be taken; the check againstnumCoursesis what catches the rest. - Several prerequisites for one course. Course 3 in
[[1, 0], [2, 0], [3, 1], [3, 2]]has an in-degree of 2 and enters the queue only after both 1 and 2 are taken. - Returning early. Returning
trueas soon as the queue first empties, or checking only whether some course starts at 0, misses cycles that don't involve every course. - Mixing up the two indices. Using
prereq[0]as the key of the list andprereq[1]as the counter builds the graph backwards. Follow the pair's meaning:[a, b]is an arrow frombtoa.
Testing
numCourses = 2,prerequisites = [[1, 0]]givestrue.numCourses = 2,prerequisites = [[1, 0], [0, 1]]givesfalse.numCourses = 4,prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]givestrue.numCourses = 3,prerequisites = [[1, 0], [2, 1], [1, 2]]givesfalse.numCourses = 3,prerequisites = []givestrue.numCourses = 1,prerequisites = []givestrue.
