In this Leetcode Course Schedule II problem solution, There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array of 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.

leetcode course schedule ii problem solution


Problem solution in Python.

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        graph = {i:[] for i in range(numCourses)}
        ourDegree = {i:0 for i in range(numCourses)}
        for i,j in prerequisites:
            graph[i].append(j)
            ourDegree[j] += 1
        
        queue = deque()
        for i in ourDegree:
            if ourDegree[i] == 0:
                queue.append(i)
                
        result = []
        while queue:
            node = queue.popleft()
            result.append(node)
            for i in graph[node]:
                ourDegree[i] -= 1
                if ourDegree[i] == 0:
                    queue.append(i)
        if len(result) != numCourses: return []
        return result[::-1]



Problem solution in Java.

int[] courses = new int[numCourses];
        Map<Integer, List<Integer>> map = new HashMap<>();
        for(int i=0; i<numCourses; i++){
            map.put(i, new ArrayList<>());
        }
        for(int[] pre: prerequisites){
            int c = pre[0], p = pre[1];
            courses[c]++;
            map.get(p).add(c);
        }
        
        Queue<Integer> q = new LinkedList<>();
        for(int i=0; i<courses.length; i++){
            if(courses[i] == 0) q.offer(i);
        }
        int[] res = new int[courses.length];
        int total = 0;
        while(q.size() > 0){
            int size = q.size();
            while(size > 0){
                int pre = q.poll();
                res[total++] = pre;
                for(int c: map.get(pre)){
                    if(--courses[c] == 0) q.offer(c);
                }
                size--;
            }
        }
        if(total != numCourses) return new int[0]; 
        return res;


Problem solution in C++.

class Solution {
public:

vector<int>result;unordered_map<int,list<int>>adjlist;
vector<bool>visited;vector<bool>instack;bool cycle=false;
void dfs(int node)
{
  visited[node]=true;
  instack[node]=true;
  for(int neighbour:adjlist[node])
  {
      if(!visited[neighbour])
          dfs(neighbour);
      else if(instack[neighbour])
      {
          cycle=true;
          return;
      }
  }
  instack[node]=false;
  result.push_back(node);
  return;
}

vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) 
{
visited.resize(numCourses);
instack.resize(numCourses);
for(int i=0;i<prerequisites.size();i++)
    adjlist[prerequisites[i][1]].push_back(prerequisites[i][0]);//Since first element in pair is dependent on second
for(int i=0;i<numCourses;i++)
{
 if(!visited[i])
 dfs(i);
 if(cycle) return {};
}
reverse(result.begin(),result.end());
return result;
}
};


Problem solution in C.

int* findOrder(int numCourses, int** prerequisites, int prerequisitesSize, int* prerequisitesColSize, int* returnSize){
    int totalnum = 0;
    int* indegree = calloc(numCourses, sizeof(int));
    int** neighbor = calloc(numCourses, sizeof(int*));
    for (int i = 0; i < numCourses; i++){
        neighbor[i] = malloc(numCourses*sizeof(int));
    }
    int* index = calloc(numCourses, sizeof(int));

    for (int i = 0; i < prerequisitesSize; i++){
        indegree[prerequisites[i][0]] += 1;
        neighbor[prerequisites[i][1]][index[prerequisites[i][1]]] = prerequisites[i][0];
        index[prerequisites[i][1]]++;
    }

    int* temp = calloc(numCourses, sizeof(int));
    int indextemp = 0;

    for (int i = 0; i < numCourses; i++){
        if (indegree[i] == 0){
            temp[indextemp] = i;
            indextemp++;
        }
    }
    int* ans = calloc(numCourses, sizeof(int));;
    int ansindex = 0;
    indextemp--;    
    while(indextemp >= 0){        
        int t = temp[indextemp];
        ans[ansindex] = t;
        ansindex++;
        indextemp--;        
        totalnum+=1;
        for (int i = 0; i < index[t]; i++){
            indegree[neighbor[t][i]]-=1; 
            if (indegree[neighbor[t][i]] == 0){
                indextemp+=1;
                temp[indextemp] = neighbor[t][i];
            }
        }
    }    
    if (totalnum == numCourses){*returnSize=totalnum; return ans;}
    *returnSize=0;
    return NULL;
}