Course Schedule
Decide whether every course can be finished when some courses must be taken before others.
There are numCoursesnumCourses - 1[a, b]prerequisites
Example 1
Output: true
Explanation: take course 0, then course 1.
Example 2
Output: false
Explanation: course 1 needs course 0 and course 0 needs course 1, so neither can be started.
Example 3
Output: true
Explanation: take course 0, then courses 1 and 2, then course 3.
The Idea
Many study programmes work like this: some courses can only be taken after others. In Example 1, the pair [1, 0]
Example 3 has more going on. Look at the left half of the picture below. Each circle is a course, and an arrow goes from a course to a course that needs it: 0 points at 1 and 2, and both 1 and 2 point at 3. The words under each circle say how many courses it still waits for.
Course 0, labelled "waits for 0", is ready now. Take it, and courses 1 and 2 each wait for one course fewer, which leaves them waiting for nothing. Take 1, and course 3 goes from waiting for 2 to waiting for 1. Take 2, and course 3 is ready too. All four courses get taken, so the answer is true.
Now look at the right half, Example 2. Course 0 needs 1 and course 1 needs 0, so each is labelled "waits for 1", and nothing is ready at the start. Neither count can ever drop, because the course each one waits for is itself waiting. Arrows that lead from a course back to the same course, here 0 to 1 and back to 0, form a cycle.
So when can every course be finished? When following the arrows never leads round in a circle. We do not have to hunt for circles directly, though. Keep taking ready courses as above and count them. A course on a cycle never becomes ready, so if the count reaches numCourses
Circles joined by one-way arrows like these are called a directed graph. The number under a circle, the count of arrows coming into it, is its in-degree. Taking ready courses one at a time and lowering the counts is known as Kahn's algorithm, and the order it gives, 0, 1, 2, 3 for Example 3, is called a topological order.
Solution Approach
Turning that idea into code means settling three things: how to store the arrows and counts, how to find ready courses without searching for them again and again, and how to tell whether every course was taken.
Storing the arrows and the counts
Which way should an arrow point? The pair [a, b]unlocks
The words "waits for" in the picture become an array, waitingFor[a, b]
Finding the ready courses
How do we know which course to take next? The simple way is to look through all the courses for one whose prerequisites are all taken. With n courses and m pairs, one such search reads all m pairs, and it may run once per course, so about n × m steps in all.
The counts avoid that. A course's count only drops when one of the courses it waits for is taken, and the course becomes ready the moment its count reaches 0. So we put it into a queue right then: a line where courses join at the back and are taken from the front. Java's ArrayDeque
Telling whether every course was taken
When does the work stop? When the queue is empty. That happens when every course is taken, but also when the remaining courses are stuck on a cycle. In Example 2 the queue is empty from the very start. An empty queue alone says nothing, so a counter, takennumCourses
Java Solution
The method canFinish
- First, build the arrows.
gets one empty list per course, and the arrayunlocks starts with a count of 0 for each course. Then a loop goes over the pairs: for each pairwaitingFor , addp to the list ofp[0] , and add one top[1] .waitingFor[p[0]] - Create the queue
, and add every course whoseready count is 0.waitingFor - Start
at 0. Ataken loop runs as long aswhile is not empty: it takes the courseready from the front and adds one toc .taken - Inside, a
loop goes over each coursefor in the list ofnext . It lowersc by one, and if the count reaches 0, addswaitingFor[next] to the back ofnext .ready - When the queue is empty, return whether
equalstaken .numCourses
The main
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
public class CourseSchedule {
public static boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> unlocks = new ArrayList<>();
for (int c = 0; c < numCourses; c++) {
unlocks.add(new ArrayList<>());
}
int[] waitingFor = new int[numCourses]; // prerequisites not taken yet
for (int[] p : prerequisites) {
unlocks.get(p[1]).add(p[0]); // taking p[1] helps unlock p[0]
waitingFor[p[0]]++;
}
Deque<Integer> ready = new ArrayDeque<>();
for (int c = 0; c < numCourses; c++) {
if (waitingFor[c] == 0) {
ready.add(c); // needs nothing: can be taken now
}
}
int taken = 0;
while (!ready.isEmpty()) {
int c = ready.poll();
taken++;
for (int next : unlocks.get(c)) {
waitingFor[next]--;
if (waitingFor[next] == 0) {
ready.add(next); // its last prerequisite is done
}
}
}
return taken == numCourses; // courses left over wait in a cycle
}
static void run(int numCourses, int[][] prerequisites) {
System.out.println("numCourses = " + numCourses + ", prerequisites = "
+ Arrays.deepToString(prerequisites)
+ " -> " + canFinish(numCourses, prerequisites));
}
public static void main(String[] args) {
run(2, new int[][] {{1, 0}});
run(2, new int[][] {{1, 0}, {0, 1}});
run(4, new int[][] {{1, 0}, {2, 0}, {3, 1}, {3, 2}});
run(3, new int[][] {});
run(1, new int[][] {{0, 0}});
run(4, new int[][] {{1, 0}, {2, 1}, {3, 2}, {1, 3}});
}
}
Running it prints:
numCourses = 2, prerequisites = [[1, 0]] -> true
numCourses = 2, prerequisites = [[1, 0], [0, 1]] -> false
numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] -> true
numCourses = 3, prerequisites = [] -> true
numCourses = 1, prerequisites = [[0, 0]] -> false
numCourses = 4, prerequisites = [[1, 0], [2, 1], [3, 2], [1, 3]] -> false
Look at the line for Example 2: [[1, 0], [0, 1]]taken[[1, 0], [2, 0], [3, 1], [3, 2]]
With prerequisites = [][0, 0]
The last line shows that one free course is not enough. Course 0 is taken and lowers course 1 from waiting for 2 to waiting for 1. But 1 needs 3, 3 needs 2 and 2 needs 1, so taken
Complexity
The work is building the lists, then one visit per course taken and one count change per arrow.
- Time: O(n + m), because building the lists reads each of the m pairs once, each of the n courses enters the queue at most once, and each arrow is followed once, when its course is taken.
- Space: O(n + m), because the
lists hold one entry per pair, whileunlocks and the queue each hold at most n courses.waitingFor
Kahn's algorithm can also return the order itself instead of a yes or no: see