Parallel Courses

Take every course whose prerequisites are done, one semester at a time, and count the semesters.

There are n courses, numbered 1 to n, and a list relations in which each entry [prev, next] says that course prev must be finished before course next can start. In one semester you may take any number of courses, as long as every course you take has all its prerequisites finished in earlier semesters. Return the smallest number of semesters needed to take every course, or -1 if that cannot be done.

Example 1
Input: n = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation: take courses 1 and 2 in the first semester, then course 3 in the second.
Example 2
Input: n = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation: course 2 needs 1, course 3 needs 2, and course 1 needs 3, so none of them can be taken first.
Solution

The Idea

A study plan at a university works like this. Some courses can be taken right away, and others list courses you must pass first. Here there is no limit on how many courses fit in one semester, so the only thing that slows you down is waiting.

In Example 1, courses 1 and 2 need nothing, and course 3 needs both. Semester 1 takes 1 and 2 together, and semester 2 takes 3. Could course 3 move into semester 1? No, because its prerequisites are not finished yet. So 2 semesters is the best.

Now add two courses to Example 1: course 4 needs nothing, and course 5 needs courses 3 and 4. Which course goes into which semester? Look at the picture below.

Five courses in three semesters. Courses 1, 2 and 4 wait for 0 courses and are taken in semester 1. Course 3 waits for 1 and 2 and is taken in semester 2. Course 5 waits for 3 and 4 and is taken in semester 3.

Each circle is a course, and each arrow goes from a prerequisite to the course that needs it. The label under a circle says how many courses it waits for. Courses 1, 2 and 4 wait for 0, so all three go into the box labelled "semester 1". Taking 1 and 2 leaves course 3 waiting for nothing, so it goes into semester 2.

Course 5, the orange circle, waits for 2 courses: 3 and 4. Course 4 is done after semester 1, but course 3 only after semester 2, so course 5 lands in semester 3. A course is ready as soon as its last prerequisite is finished, and not earlier.

Is it ever better to hold a ready course back? No. Taking it early uses no space anyone else needs, and it can only let the courses that need it start sooner. So the plan is simple: in every semester, take every course that is ready, and count the semesters.

The answer also has a second reading. The chain 1, 3, 5 is three courses, each needing the one before, so no plan can finish it in fewer than 3 semesters. Taking every ready course reaches exactly that: the number of semesters is the number of courses on the longest chain of prerequisites.

What about Example 2? Course 1 waits for 3, course 3 waits for 2, and course 2 waits for 1. Going round like this, back to where you started, is called a cycle. None of the three is ever ready, so semester 1 is empty and the answer is -1.

Solution Approach

Turning that idea into code means settling three things: how to store the relations, how to find the courses of each semester without checking everything again, and how to notice a cycle.

Storing the relations

What does the code need to know when a course is taken? Two things: which courses it brings closer, and how many courses each course still waits for. Courses and arrows like the ones in the picture form a graph, and a common way to store one is a list per course of where its arrows lead, called an adjacency list.

For the picture, the lists read: 1 leads to [3], 2 leads to [3], 3 leads to [5], 4 leads to [5], and 5 leads to []. Next to them, an array holds the "waits for" numbers from the picture: 0, 0, 2, 0, 2 for courses 1 to 5. The number of arrows pointing into a course is usually called its indegree.

Finding each semester's courses

Which courses are ready next semester? The simple way is to look at every course not yet taken and check all its prerequisites, every semester. With a long chain that means reading all the relations once for each of up to n semesters.

The "waits for" counts avoid that. When a course is taken, follow its arrows and lower the count of each course they lead to by 1. A course whose count reaches 0 has just lost its last prerequisite, so it belongs to the next semester. Only those courses need to be looked at.

So the code keeps the courses of the current semester in one list and collects the next semester's courses in a new list while it works through them. Repeatedly taking the courses whose count is 0 and lowering the counts of the rest is known as Kahn's algorithm, and it orders the courses so that every course comes after its prerequisites.

Noticing a cycle

How does the code know the plan is impossible? Courses on a cycle never reach a count of 0, so they never enter any semester, and the loop just stops when a semester comes out empty. Counting the courses taken and comparing that number with n tells the two cases apart.

Java Solution

The method minimumSemesters works in these steps:

  1. First, build the adjacency list unlocks, with one list per course, and the array waitingFor of counts. Both have n + 1 slots, so course c sits at index c. For each relation [prev, next], add next to the list of prev and add 1 to the count of next.
  2. Fill the list current with every course whose count is 0. These are the courses of semester 1.
  3. While current is not empty, add 1 to semesters and add the size of current to taken, the number of courses taken so far.
  4. Inside that loop, start an empty list following. For each course in current, go through its list in unlocks and lower each count by 1. A course whose count reaches 0 goes into following. Then following becomes the new current.
  5. When the loop ends, return semesters if taken equals n, and -1 otherwise.

The main method runs both examples, the five courses from the picture, a straight chain of four courses, three courses with no relations, and four courses where only courses 3 and 4 form a cycle.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ParallelCourses {

    public static int minimumSemesters(int n, int[][] relations) {
        List<List<Integer>> unlocks = new ArrayList<>();
        for (int c = 0; c <= n; c++) {
            unlocks.add(new ArrayList<>());   // slot 0 stays empty: courses are 1 to n
        }
        int[] waitingFor = new int[n + 1];
        for (int[] r : relations) {
            unlocks.get(r[0]).add(r[1]);      // taking r[0] brings r[1] one step closer
            waitingFor[r[1]]++;
        }

        List<Integer> current = new ArrayList<>();
        for (int c = 1; c <= n; c++) {
            if (waitingFor[c] == 0) {
                current.add(c);               // no prerequisites: ready in semester 1
            }
        }
        int semesters = 0;
        int taken = 0;
        while (!current.isEmpty()) {
            semesters++;
            taken += current.size();
            List<Integer> following = new ArrayList<>();
            for (int c : current) {
                for (int d : unlocks.get(c)) {
                    waitingFor[d]--;
                    if (waitingFor[d] == 0) {
                        following.add(d);     // its last prerequisite was just taken
                    }
                }
            }
            current = following;
        }
        return taken == n ? semesters : -1;   // courses left over wait on a cycle
    }

    static void run(int n, int[][] relations) {
        System.out.println("n = " + n + ", relations = " + Arrays.deepToString(relations)
                + " -> " + minimumSemesters(n, relations));
    }

    public static void main(String[] args) {
        run(3, new int[][] {{1, 3}, {2, 3}});
        run(3, new int[][] {{1, 2}, {2, 3}, {3, 1}});
        run(5, new int[][] {{1, 3}, {2, 3}, {3, 5}, {4, 5}});
        run(4, new int[][] {{1, 2}, {2, 3}, {3, 4}});
        run(3, new int[][] {});
        run(4, new int[][] {{1, 2}, {3, 4}, {4, 3}});
    }
}

Running it prints:

Output
n = 3, relations = [[1, 3], [2, 3]] -> 2
n = 3, relations = [[1, 2], [2, 3], [3, 1]] -> -1
n = 5, relations = [[1, 3], [2, 3], [3, 5], [4, 5]] -> 3
n = 4, relations = [[1, 2], [2, 3], [3, 4]] -> 4
n = 3, relations = [] -> 1
n = 4, relations = [[1, 2], [3, 4], [4, 3]] -> -1

The third line is the picture: 3 semesters, the length of the chain 1, 3, 5. The chain [[1, 2], [2, 3], [3, 4]] gives 4, one course per semester, because each course is ready only after the one before it. With no relations at all, every course is ready at once, so three courses take 1 semester.

Look at the last line. Courses 1 and 2 are fine, and semesters 1 and 2 take them, but 3 and 4 wait for each other. The loop stops after 2 semesters with taken at 2, not 4, so the method returns -1. Without the final check against n, this input returns 2 and Example 2 returns 0, as a test run of that version showed: the courses on the cycle are silently left out.

Complexity

The work is building the lists once and then taking each course once. Write E for the number of relations.

  • Time: O(n + E), because each relation is read once to build unlocks, each course enters current at most once, and each arrow is followed only when its prerequisite is taken.
  • Space: O(n + E), because the lists in unlocks hold one entry per relation, waitingFor has a slot per course, and current and following together never hold more than n courses.

When the question is only whether all courses can be taken, not how many semesters it takes, see Course Schedule.