Medium
Subtopics
breadth-first-search·depth-first-search·graph·topological-sort
Companies
airbnb·amazon·apple·bloomberg·doordash·facebook·google·intuit·microsoft·nutanix·oracle·pinterest·snapchat·twitter·uber·wayfair·zenefitsLast updated: Aug 2, 2025
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 course 0 you have to first take course 1.
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.
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'].
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:
1
2
3
4
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].
publicint[]findOrder(int numCourses, int[][] prerequisites) {
if (prerequisites ==null) {
thrownew IllegalArgumentException("illegal prerequisites array");
}
int len = prerequisites.length;
//if there is no prerequisites, return a sequence of coursesif (len == 0) {
int[] res =newint[numCourses];
for (int m = 0; m<numCourses; m++) {
res[m]= m;
}
return res;
}
//records the number of prerequisites each course (0,...,numCourses-1) requiresint[] pCounter =newint[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 resultint[] result =newint[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 resultif (numNoPre == numCourses) {
return result;
} else {
returnnewint[0];
}
}
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.
🧺 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.
publicint[]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 wellfor (int i = 0; i<numCourses; i++){
if(!dfs(i, graph, visiting, visited)){
returnnewint[0];
}
}
int[] ans =newint[visited.size()];
int i = 0;
for (int num : visited) {
ans[i++]= num;
}
return ans;
}
publicbooleandfs(int crs, Map<Integer, Set<Integer>> graph, Set<Integer> visiting, Set<Integer> visited){
// we are still visiting, but we find it againif(visiting.contains(crs)){
returnfalse;
}
if(visited.contains(crs)){
returntrue;
}
visiting.add(crs);
for(int pre: graph.get(crs)){
// if returns false, that means a cycleif(!dfs(pre, graph, visiting, visited)){
returnfalse;
}
}
// no cycle encountered from crs as starting node visiting.remove(crs);
visited.add(crs);
returntrue;
}