Course Schedule II LeetCode Solution

Last updated on February 2nd, 2025 at 05:50 am

Here, we see a Course Schedule II LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Breadth-First Search, Depth-First Search, Graph, Topological Sort

Companies

Facebook, Zenefits

Level of Question

Medium

Course Schedule II LeetCode Solution

Course Schedule II LeetCode Solution

1. Problem Statement

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.

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]

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is Topological Sort. Topological Sort is a graph-based algorithm used to determine the order of tasks (or nodes) in a Directed Acyclic Graph (DAG) such that for every directed edge u -> v, node u comes before node v in the ordering. This is commonly used in problems like course scheduling, dependency resolution, and task ordering.

3. Code Implementation in Different Languages

3.1 Course Schedule II C++

class Solution{
public:
    bool kahnAlgo(vector<vector<int>> &adj, int n, vector<int> &indegree, vector<int> &ans)
    {
        queue<int> q;
        for (int i = 0; i < n; i++)
        {
            if (indegree[i] == 0)
                q.push(i);
        }
        int count = 0;
        while (!q.empty()){
            int curr = q.front();
            q.pop();
            for (auto a : adj[curr]){
                indegree[a] -= 1;
                if (indegree[a] == 0)
                    q.push(a);
            }
            ans.push_back(curr);
            count++;
        }
        if (count != n)
            return false;
        return true;
    }

    vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
    {
        int n = prerequisites.size();
        vector<vector<int>> adj(numCourses);
        vector<int> indegree(numCourses, 0);
        for (int i = 0; i < n; i++){
            adj[prerequisites[i][1]].push_back(prerequisites[i][0]);
            indegree[prerequisites[i][0]] += 1;
        }
        vector<int> ans;
        if (kahnAlgo(adj, numCourses, indegree, ans))
            return ans;
        return {};
    }
};

3.2 Course Schedule II Java

class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] inDeg = new int[numCourses];
        List<Integer>[] chl = new ArrayList[numCourses];
        for (int i = 0; i < numCourses; i++) {
            chl[i] = new ArrayList<Integer>();
        }
        int pre;
        int cour;
        for (int[] pair : prerequisites) {
            pre = pair[1];
            cour = pair[0];
            chl[pre].add(cour);
            inDeg[cour]++;
        }
        int[] res = new int[numCourses];
        int k = 0;
        for (int i = 0; i < numCourses; i++) {
            if (inDeg[i] == 0) {
                res[k++] = i;
            }
        }
        if (k == 0) {
            return new int[0];
        }
        int j = 0;
        List<Integer> tmp;
        while (k < numCourses) {
            tmp = chl[res[j++]];
            for (int id : tmp) {
                if (--inDeg[id] == 0) {
                    res[k++] = id;
                }
            }
            if (j == k) {
                return new int[0];
            }
        }
        return res;
    }
}

3.3 Course Schedule II JavaScript

var findOrder = function(numCourses, prerequisites) {
    const order = [];
    const queue = [];
    const graph = new Map();
    const indegree = Array(numCourses).fill(0);
    for (const [e, v] of prerequisites) {
        if (graph.has(v)) {
        graph.get(v).push(e);
        } else {
        graph.set(v, [e]);
        }
        indegree[e]++;
    }
    for (let i = 0; i < indegree.length; i++) {
        if (indegree[i] === 0) queue.push(i);
    }
    while (queue.length) {
        const v = queue.shift();
        if (graph.has(v)) {
        for (const e of graph.get(v)) {
            indegree[e]--;
            if (indegree[e] === 0) queue.push(e);
        }
        }
        order.push(v);
    }
    return numCourses === order.length ? order : [];
};

3.4 Course Schedule II Python

class Solution(object):
    def findOrder(self, numCourses, prerequisites):
        self.graph = collections.defaultdict(list)
        self.res = []
        for pair in prerequisites:
            self.graph[pair[0]].append(pair[1]) 
        self.visited = [0 for x in xrange(numCourses)]
        for x in xrange(numCourses):
            if not self.DFS(x):
                return []
        return self.res
    
    def DFS(self, node):
        if self.visited[node] == -1:
            return False
        if self.visited[node] == 1:
            return True
        self.visited[node] = -1
        for x in self.graph[node]:
            if not self.DFS(x):
                return False
        self.visited[node] = 1
        self.res.append(node)
        return True

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(V + E)O(V + E)
JavaO(V + E)O(V + E)
JavaScriptO(V + E)O(V + E)
PythonO(V + E)O(V + E)

where,
V: Number of courses (nodes).
E: Number of prerequisites (edges).

Scroll to Top