Question
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.
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]
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= numCourses * (numCourses - 1)
prerequisites[i].length == 2
0 <= ai, bi < numCourses
ai != bi
- All the pairs
[ai, bi]
are distinct.
Algorithm
- Typical topological sort question, there are two ways of solving it, using BFS or DFS.
- BFS is much more easier to understand and memorize.
- The algorithm is like
- You loop all the dependencies and record the in degree for each node (the in degree is how many edges going to the current vertex, how many are in the node)
- Then a normal BFS, start from those has 0 in degree, which mean those has no prerequisite,
- After going through those, they might be others dependency/prerequisite , so check the dependency list and maintain the in degree, -> we learn the course , so we decrease the indegree.
- When all the prerequisite is learnt , which means the in degree is 0, we add courses to the queue again to do another round of loop("learning")
- In the end, we check if the final result has as many course as start (there will be loop so that not all the courses can be learnt)
Implementation
class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { int[] indegrees = new int[numCourses]; for (int[] pre : prerequisites) { int course = pre[0]; int prerequisite = pre[1]; indegrees[course]++; } Queue<Integer> queue = new LinkedList<>(); int[] res = new int[numCourses]; int k = 0; for (int i = 0; i < numCourses; i++) { if (indegrees[i] == 0) { queue.offer(i); res[k++] = i; } } while (!queue.isEmpty()) { int current = queue.poll(); for (int[] pre : prerequisites) { int course = pre[0]; int prerequisite = pre[1]; if (current == prerequisite) { indegrees[course]--; if (indegrees[course] == 0) { queue.offer(course); res[k++] = course; } } } } return k == numCourses ? res : new int[]{}; } }
- Time Complexity: O(V+E) where VVV represents the number of vertices and E represents the number of edges. We pop each node exactly once from the zero in-degree queue and that gives us V. Also, for each vertex, we iterate over its adjacency list and in totality, we iterate over all the edges in the graph which gives us EEE. Hence, O(V+E)
- Space Complexity: O(V+E). The in-degree array requires O(V) space. We use an intermediate queue data structure to keep all the nodes with 0 in-degree. In the worst case, there won't be any prerequisite relationship and the queue will contain all the vertices initially since all of them will have 0 in-degree. That gives us O(V). Additionally, we also use the adjacency list to represent our graph initially. The space occupied is defined by the number of edges because for each node as the key, we have all its adjacent nodes in the form of a list as the value. Hence, O(E)). So, the overall space complexity is O(V+E).