Parallel Courses
Take every course whose prerequisites are done, one semester at a time, and count the semesters.
There are nnrelations[prev, next]prevnext
Example 1
Output: 2
Explanation: take courses 1 and 2 in the first semester, then course 3 in the second.
Example 2
Output: -1
Explanation: course 2 needs 1, course 3 needs 2, and course 1 needs 3, so none of them can be taken first.
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.
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
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
Java Solution
The method minimumSemesters
- First, build the adjacency list
, with one list per course, and the arrayunlocks of counts. Both havewaitingFor slots, so coursen + 1 sits at indexc . For each relationc , add[prev, next] to the list ofnext and add 1 to the count ofprev .next - Fill the list
with every course whose count is 0. These are the courses of semester 1.current - While
is not empty, add 1 tocurrent and add the size ofsemesters tocurrent , the number of courses taken so far.taken - Inside that loop, start an empty list
. For each course infollowing , go through its list incurrent and lower each count by 1. A course whose count reaches 0 goes intounlocks . Thenfollowing becomes the newfollowing .current - When the loop ends, return
ifsemesters equalstaken , and -1 otherwise.n
The main
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:
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]]
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 takenn
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
, each course entersunlocks at most once, and each arrow is followed only when its prerequisite is taken.current - Space: O(n + E), because the lists in
hold one entry per relation,unlocks has a slot per course, andwaitingFor andcurrent together never hold more thanfollowing courses.n
When the question is only whether all courses can be taken, not how many semesters it takes, see