Problem
There are a total of numCourses
courses you have to take, labeled from 0
to numCourses - 1
. You are given an array prerequisites
where prerequisites[i] = [ai, bi]
indicates that you must take course bi
first if you want to take course ai
.
- For example, the pair
[0, 1]
, indicates that to take course0
you have to first take course1
.
Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
This is extension of Course Schedule 1 - Is it Possible.
Similar Problem
We’re given a hashmap associating each courseId
key with a list of courseIds
values, which represents that the prerequisites of courseId
are courseIds
. Return a sorted ordering of courses such that we can finish all courses.
Return null if there is no such ordering.
For example, given {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}, should return ['CSC100', 'CSC200', 'CSCS300']
.
Examples
Example 1:
Input: numCourses = 2, prerequisites =[[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
Example 2:
Input: numCourses = 4, prerequisites =[[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
Example 3:
Input: numCourses = 1, prerequisites = []
Output: [0]
Solution
Method 1 - BFS on Graph
This is similar to Topological Sorting. We need to figure out if there is no cycle, then we have the course list in topological order.
Here we are using array pCounter
as map to track the dependency between courses, which are like nodes in graph.
Code
Java
public int[] findOrder(int numCourses, int[][] prerequisites) {
if (prerequisites == null) {
throw new IllegalArgumentException("illegal prerequisites array");
}
int len = prerequisites.length;
//if there is no prerequisites, return a sequence of courses
if (len == 0) {
int[] res = new int[numCourses];
for (int m = 0; m<numCourses; m++) {
res[m] = m;
}
return res;
}
//records the number of prerequisites each course (0,...,numCourses-1) requires
int[] pCounter = new int[numCourses];
for (int i = 0; i<len; i++) {
pCounter[prerequisites[i][0]]++;
}
//stores courses that have no prerequisites
LinkedList<Integer> queue = new LinkedList<Integer> ();
for (int i = 0; i<numCourses; i++) {
if (pCounter[i] == 0) {
queue.add(i);
}
}
int numNoPre = queue.size();
//initialize result
int[] result = new int[numCourses];
int j = 0;
while (!queue.isEmpty()) {
int c = queue.remove();
result[j++] = c;
for (int i = 0; i<len; i++) {
if (prerequisites[i][1] == c) {
pCounter[prerequisites[i][0]]--;
if (pCounter[prerequisites[i][0]] == 0) {
queue.add(prerequisites[i][0]);
numNoPre++;
}
}
}
}
//return result
if (numNoPre == numCourses) {
return result;
} else {
return new int[0];
}
}
Complexity
- ⏰ Time complexity:
O(E + V)
- We iterate through the
prerequisites
array once to count the number of prerequisites for each course, which takes ( O(E) ) time, where ( E ) is the total number of prerequisites. - We iterate through all courses to add those with zero prerequisites to the queue, which takes ( O(V) ) time, where ( V ) is the number of courses.
- The while loop runs until the queue is empty, processing each course once. Inside the loop, for each course removed, we again iterate through all prerequisites. In the worst case, this nested iteration checks each prerequisite once for each course, which takes ( O(V \cdot E) ) time. However, since each prerequisite involves a constant amount of work, this will actually be ( O(V + E) ) in amortized time.
- We iterate through the
- 🧺 Space complexity:
O(V)
- The
pCounter
array takes ( O(V) ) space to store the prerequisite counts for each course. - In the worst case, the queue can contain all ( V ) courses, thus taking ( O(V) ) space.
- The
result
array stores the topological order of the courses and takes ( O(V) ) space. - The stack space used by the LinkedList operations in the worst scenario might be considered, but it is minimal compared to the main data structures.
- The
Method 2 - Using DFS
We will use hashset to go through graph, track path; and when we encounter the same node again, that means we have a cycle. So, we return 0.
Now, each node has 3 states:
- Visited - Course has been added to output
- Visiting - Course has not yet added to output, but added to check cycle
- Unvisited - Course is yet not processed
Code
Java
public int[] findOrder(int numCourses, int[][] prerequisites) {
int len = prerequisites.length;
// course directed graph
Map<Integer, Set<Integer>> graph = new HashMap<>();
for(int i = 0; i < numCourses; i++){
graph.put(i, new HashSet<>());
}
for (int[] courseDep: prerequisites){
int crs = courseDep[0];
int pre = courseDep[1];
graph.get(crs).add(pre);
}
Set<Integer> visiting = new HashSet<>();
Set<Integer> visited = new LinkedHashSet<>();// we care about order as well
for (int i = 0; i<numCourses; i++){
if(!dfs(i, graph, visiting, visited)){
return new int[0];
}
}
int[] ans = new int[visited.size()];
int i = 0;
for (int num : visited) {
ans[i++] = num;
}
return ans;
}
public boolean dfs(int crs, Map<Integer, Set<Integer>> graph, Set<Integer> visiting, Set<Integer> visited){
// we are still visiting, but we find it again
if(visiting.contains(crs)){
return false;
}
if(visited.contains(crs)){
return true;
}
visiting.add(crs);
for(int pre: graph.get(crs)){
// if returns false, that means a cycle
if(!dfs(pre, graph, visiting, visited)){
return false;
}
}
// no cycle encountered from crs as starting node
visiting.remove(crs);
visited.add(crs);
return true;
}
Complexity
- ⏰ Time complexity:
O(V+E)
- Graph creation takes O(E) time
- DFS traversal takes O(E+V) time
- 🧺 Space complexity:
O(V + E)
- Adjacency list takes O(E+V) space
- Visiting and visited set takes O(V) space
- Recursion stack takes O(V)