Welcome to Subscribe On Youtube

Question

Formatted question description: https://leetcode.ca/all/210.html

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]

 

Constraints:

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • ai != bi
  • All the pairs [ai, bi] are distinct.

Algorithm

Topological Sort of directed graph, in this way, the difficulty increases,

Due to the basis of the previous one, with a slight modification, every time an array is removed from the queue, it is stored in the result.

In the end, if there is a cycle in the directed graph, the number of elements in the result is not equal to the total number of courses, then we clear the result.

Code

  • import java.util.*;
    
    public class Course_Schedule_II {
    
        public static void main(String[] args) {
            Course_Schedule_II out = new Course_Schedule_II();
            Solution s = out.new Solution();
    
            System.out.println(Arrays.toString(s.findOrder(2, new int[][]{ {1,0} })));
        }
    
        class Solution {
            public int[] findOrder(int numCourses, int[][] prerequisites) {
    
                if(numCourses <= 0) {
                    return new int[0];
                }
    
                if(prerequisites == null) {
                    return new int[numCourses];
                }
    
                int[] inDegree = new int[numCourses];
                for (int[] each: prerequisites) {
                    inDegree[each[0]]++;
                }
    
                Queue<Integer> q = new LinkedList<>();
                for (int i = 0; i < inDegree.length; i++) {
                    if (inDegree[i] == 0) {
                        q.offer(i);
                    }
                }
    
                List<Integer> result = new ArrayList<>();
                while (!q.isEmpty()) {
                    int current = q.poll();
                    result.add(current);
    
                    for (int[] each: prerequisites) {
                        if (current == each[1]) {
                            inDegree[each[0]]--;
    
                            if (inDegree[each[0]] == 0) {
                                q.offer(each[0]);
                            }
                        }
                    }
                }
    
                if(!(result.size() == numCourses)) {
                    return new int[0];
                }
    
                return result.stream().mapToInt(i -> i).toArray();
            }
        }
    
        class Solution2 {
            public int[] findOrder(int numCourses, int[][] prerequisites) {
    
                if (numCourses <= 0 || prerequisites == null) {
                    return new int[0];
                }
    
                // construct graph
                int[] incomingCount = new int[numCourses];
                List<List<Integer>> g = new ArrayList<>(numCourses);
    
                constructGraph(numCourses, prerequisites, g, incomingCount);
    
                // bfs or dfs
                return bfs(numCourses, g, incomingCount);
            }
    
            private int[] bfs(int numCourses, List<List<Integer>> g, int[] incomingCount) {
    
                int[] result = new int[numCourses];
    
                Queue<Integer> q = new LinkedList<>();
    
                // search for starting point
                for (int i = 0; i < numCourses; i++) {
                    if (incomingCount[i] == 0) {
                        q.offer(i); // could be multiple node without incoming
                    }
                }
    
                int resultPointer = 0;
                while (!q.isEmpty()) {
                    int node = q.poll();
                    result[resultPointer++] = node;
                    for (int each: g.get(node)) {
                        incomingCount[each]--;
                        if (incomingCount[each] == 0) {
                            q.offer(each);
                        }
                    }
                }
    
                // @note: how to check valid result
                return resultPointer == numCourses ? result : new int[0];
            }
    
            private void constructGraph(int numCourses, int[][] prerequisites, List<List<Integer>> g, int[] incomingCount) {
    
                // empty graph
                for (int i = 0; i < numCourses; i++) {
                    g.add(new ArrayList<Integer>());
                }
    
                for (int[] pair: prerequisites) {
                    incomingCount[pair[0]]++;
                    g.get(pair[1]).add(pair[0]);
                }
            }
        }
    }
    
    ############
    
    class Solution {
        public int[] findOrder(int numCourses, int[][] prerequisites) {
            List<Integer>[] g = new List[numCourses];
            Arrays.setAll(g, k -> new ArrayList<>());
            int[] indeg = new int[numCourses];
            for (var p : prerequisites) {
                int a = p[0], b = p[1];
                g[b].add(a);
                ++indeg[a];
            }
            Deque<Integer> q = new ArrayDeque<>();
            for (int i = 0; i < numCourses; ++i) {
                if (indeg[i] == 0) {
                    q.offer(i);
                }
            }
            int[] ans = new int[numCourses];
            int cnt = 0;
            while (!q.isEmpty()) {
                int i = q.poll();
                ans[cnt++] = i;
                for (int j : g[i]) {
                    if (--indeg[j] == 0) {
                        q.offer(j);
                    }
                }
            }
            return cnt == numCourses ? ans : new int[0];
        }
    }
    
  • // OJ: https://leetcode.com/problems/course-schedule-ii/
    // Time: O(V + E)
    // Space: O(V + E)
    class Solution {
    public:
        vector<int> findOrder(int n, vector<vector<int>>& E) {
            vector<vector<int>> G(n);
            vector<int> indegree(n), ans;
            for (auto &e : E) {
                G[e[1]].push_back(e[0]);
                indegree[e[0]]++;
            }
            queue<int> q;
            for (int i = 0; i < n; ++i) {
                if (indegree[i] == 0) q.push(i);
            }
            while (q.size()) {
                int u = q.front();
                q.pop();
                ans.push_back(u);
                for (int v : G[u]) {
                    if (--indegree[v] == 0) q.push(v);
                }
            }
            return ans.size() == n ? ans : vector<int>{};
        }
    };
    
  • class Solution:
        def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
            g = defaultdict(list)
            indeg = [0] * numCourses
            for a, b in prerequisites:
                g[b].append(a)
                indeg[a] += 1
            q = deque([i for i, v in enumerate(indeg) if v == 0])
            ans = []
            while q:
                i = q.popleft()
                ans.append(i)
                # assumption is only one path
                # as in question 'You may assume that there are no duplicate edges in the input prerequisites.'
                for j in g[i]:
                    indeg[j] -= 1
                    if indeg[j] == 0:
                        q.append(j)
            return ans if len(ans) == numCourses else []
    
    ############
    
    class Solution(object):
      def findOrder(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: List[int]
        """
    
        def dfs(start, visited, graph, ans):
          visited[start] = 1
          for nbr in graph[start]:
            if visited[nbr] == 1:
              return False
            if visited[nbr] != 0:
              continue
            if dfs(nbr, visited, graph, ans) == False:
              return False
          ans.append(start)
          visited[start] = 2
          return True
    
        graph = [[] for _ in range(0, numCourses)]
        ans = []
    
        for pre in prerequisites:
          start, end = pre
          graph[start].append(end)
    
        visited = [0 for _ in range(0, numCourses)]
    
        for pre in prerequisites:
          start, end = pre
          if visited[start] != 0:
            continue
          if dfs(start, visited, graph, ans) == False:
            return []
        for i in range(0, numCourses):
          if visited[i] == 0:
            ans.append(i)
        return ans
    
    
  • func findOrder(numCourses int, prerequisites [][]int) []int {
    	g := make([][]int, numCourses)
    	indeg := make([]int, numCourses)
    	for _, p := range prerequisites {
    		a, b := p[0], p[1]
    		g[b] = append(g[b], a)
    		indeg[a]++
    	}
    	q := []int{}
    	for i, v := range indeg {
    		if v == 0 {
    			q = append(q, i)
    		}
    	}
    	ans := []int{}
    	for len(q) > 0 {
    		i := q[0]
    		q = q[1:]
    		ans = append(ans, i)
    		for _, j := range g[i] {
    			indeg[j]--
    			if indeg[j] == 0 {
    				q = append(q, j)
    			}
    		}
    	}
    	if len(ans) == numCourses {
    		return ans
    	}
    	return []int{}
    }
    
  • function findOrder(numCourses: number, prerequisites: number[][]): number[] {
        let g = Array.from({ length: numCourses }, () => []);
        let indeg = new Array(numCourses).fill(0);
        for (let [a, b] of prerequisites) {
            g[b].push(a);
            ++indeg[a];
        }
        let q = [];
        for (let i = 0; i < numCourses; ++i) {
            if (!indeg[i]) {
                q.push(i);
            }
        }
        let ans = [];
        while (q.length) {
            const i = q.shift();
            ans.push(i);
            for (let j of g[i]) {
                if (--indeg[j] == 0) {
                    q.push(j);
                }
            }
        }
        return ans.length == numCourses ? ans : [];
    }
    
    
  • public class Solution {
        public int[] FindOrder(int numCourses, int[][] prerequisites) {
            var g = new List<int>[numCourses];
            for (int i = 0; i < numCourses; ++i)
            {
                g[i] = new List<int>();
            }
            var indeg = new int[numCourses];
            foreach (var p in prerequisites)
            {
                int a = p[0], b = p[1];
                g[b].Add(a);
                ++indeg[a];
            }
            var q = new Queue<int>();
            for (int i = 0; i < numCourses; ++i)
            {
                if (indeg[i] == 0) q.Enqueue(i);
            }
            var ans = new int[numCourses];
            var cnt = 0;
            while (q.Count > 0)
            {
                int i = q.Dequeue();
                ans[cnt++] = i;
                foreach (int j in g[i])
                {
                    if (--indeg[j] == 0) q.Enqueue(j);
                }
            }
            return cnt == numCourses ? ans : new int[0];
        }
    }
    

All Problems

All Solutions