Posts Course Schedule II
Post
Cancel

Course Schedule II

Problem Description

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.

leetcode

Solution

Refer to the following solution to understand the main idea: Course Schedule

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
    
    public int[] findOrder(int numCourses, int[][] prerequisites) {

        //create adjacency list using prerequisites
        ArrayList<Integer>[] adj = new ArrayList[numCourses];
        for(int i=0; i<numCourses; i++){
            adj[i] = new ArrayList<Integer>();
        }
        for(int i=0; i<prerequisites.length; i++){
            adj[prerequisites[i][0]].add(prerequisites[i][1]);
        }

        //in-degree
        int[] indegree = new int[numCourses];
        for(int i=0; i<prerequisites.length; i++){
            indegree[prerequisites[i][1]]++;
        }

        //add nodes with in-degree 0 to a queue
        Queue<Integer> q = new LinkedList<>();
        for(int i=0; i<numCourses; i++){
            if(indegree[i] == 0){
                q.add(i);
            }
        }

        int processed = 0;
        int[] ans = new int[numCourses];

        while(!q.isEmpty()){

            Integer x = q.poll();
            ans[processed] = x;
            processed++;
            List<Integer> neighbours = adj[x];

            //indegree of neighbours of x will decrease by 1
            for(int i=0; i<neighbours.size(); i++){
                
                indegree[neighbours.get(i)]--;

                //If it's 0, add to queue
                if(indegree[neighbours.get(i)] == 0){
                    q.add(neighbours.get(i));
                }

            }

        }

        //The actual answer will be reverse of ans[]
        int[] convertedAns = new int[numCourses];
        for(int i=0; i<numCourses; i++){
            convertedAns[i] = ans[numCourses-i-1];
        }

        if(processed == numCourses)
            return convertedAns;
        else
            return new int[]{};
    }
}
This post is licensed under CC BY 4.0 by the author.