Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Course Schedule II problem solution

YASH PAL, 31 July 2024

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;
}

coding problems

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
How to download udemy paid courses for free

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
©2025 Programming101 | WordPress Theme by SuperbThemes