Course Schedule

Decide whether every course can be finished when some courses must be taken before others.

There are numCourses courses, numbered 0 to numCourses - 1. Each entry [a, b] in the array prerequisites means that course b must be taken before course a. Return true if every course can be finished, and false otherwise.

Example 1
Input: numCourses = 2, prerequisites = [[1, 0]]
Output: true
Explanation: take course 0, then course 1.
Example 2
Input: numCourses = 2, prerequisites = [[1, 0], [0, 1]]
Output: false
Explanation: course 1 needs course 0 and course 0 needs course 1, so neither can be started.
Example 3
Input: numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
Output: true
Explanation: take course 0, then courses 1 and 2, then course 3.
Solution

The Idea

Many study programmes work like this: some courses can only be taken after others. In Example 1, the pair [1, 0] says that course 1 needs course 0 first, so you take 0 and then 1, and both are done.

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.

Left: Example 3, four courses with arrows from 0 to 1, 0 to 2, 1 to 3 and 2 to 3. Course 0 waits for 0 and is ready now, 1 and 2 wait for 1, 3 waits for 2. Right: Example 2, courses 0 and 1 point at each other, each waits for 1, and nothing is ready.

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, there was no cycle.

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] means a needs b. When b is taken, we must reach every course that waits on b, so the arrow goes from b to a. For each course, a list called unlocks holds the courses its arrows point at. For course 0 in Example 3, that list is 1 and 2.

The words "waits for" in the picture become an array, waitingFor, with one count per course. Each pair [a, b] adds one to the count of a.

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 works as one. At the start, the queue holds every course whose count is already 0.

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, taken, counts the courses taken, and the answer is whether it equals numCourses.

Java Solution

The method canFinish works in these steps:

  1. First, build the arrows. unlocks gets one empty list per course, and the array waitingFor starts with a count of 0 for each course. Then a loop goes over the pairs: for each pair p, add p[0] to the list of p[1], and add one to waitingFor[p[0]].
  2. Create the queue ready, and add every course whose waitingFor count is 0.
  3. Start taken at 0. A while loop runs as long as ready is not empty: it takes the course c from the front and adds one to taken.
  4. Inside, a for loop goes over each course next in the list of c. It lowers waitingFor[next] by one, and if the count reaches 0, adds next to the back of ready.
  5. When the queue is empty, return whether taken equals numCourses.

The main method runs the three examples, three courses with no prerequisites, a course that requires itself, and four courses where 1, 2 and 3 wait on each other in a circle while 0 is free.

Java
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:

Output
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]] gives false, because the queue starts empty and taken stays at 0. Example 3, with [[1, 0], [2, 0], [3, 1], [3, 2]], gives true, because all four courses get taken, just as in the walk through the picture.

With prerequisites = [], every count starts at 0, so all three courses are ready at once and the result is true. The pair [0, 0] makes course 0 wait for itself: its count starts at 1, and only taking course 0 could lower it, so the result is false.

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 stops at 1 out of 4 and the method returns false.

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 unlocks lists hold one entry per pair, while waitingFor and the queue each hold at most n courses.

Kahn's algorithm can also return the order itself instead of a yes or no: see Topological Sort.