Problem
Section titled “Problem”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] = [a_i, b_i] indicates that you must take course b_i first if you want to take course a_i.
- For example, the pair
[0, 1], indicates that to take course0you have to first take course1.
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:
-
numCourses -
prerequisites.lengthnumCourses * (numCourses - 1) prerequisites[i].length == 2-
numCourses - All the pairs
[a_i, b_i]are distinct.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Draw an edge b → a for every pair [a, b] (“b unlocks a”). A valid order is exactly a topological order of this directed graph, and one exists if and only if the graph has no cycle.
Kahn’s algorithm builds the order greedily. A course whose in-degree (number of unmet prerequisites) is 0 can be taken right now. Take it, and “remove” its outgoing edges by decrementing the in-degree of every course it unlocks; any course that drops to 0 becomes available. If the graph has a cycle, the courses on it always keep at least one unmet prerequisite (another course on the cycle), so they never reach in-degree 0 and the order ends up shorter than numCourses.
Algorithm
Section titled “Algorithm”- Build
adjwith an edgepre[1] → pre[0]for every pair, and countindeg[pre[0]]. - Put every course with
indeg == 0intoorder.orderdoubles as the BFS queue:headis the index of the next course to process. - While
head < order.size(): for eachvinadj[order[head]], decrementindeg[v], and appendvtoorderwhen it reaches0; then advancehead. Everything inorderis a course whose prerequisites all appear before it. - If
order.size() == numCourses, returnorder; otherwise a cycle blocked some courses, so return an empty array.
Walkthrough
Section titled “Walkthrough”Example 2. In-degrees start at 0:0, 1:1, 2:1, 3:2. Course 0 is taken first and unlocks 1 and 2; course 3 only becomes available after both 1 and 2 are taken.
The code produces [0, 1, 2, 3], which is one of the accepted answers.
Complexity
Section titled “Complexity”- Time: — building the graph touches each pair once, and each course enters
orderat most once, with its edges scanned once. - Space: — the adjacency list plus
indegandorder.
Edge cases
Section titled “Edge cases”- No prerequisites: every course starts with in-degree
0, soorderis0, 1, ..., numCourses - 1. - A cycle anywhere (for example
[[1,0],[0,1]]): the courses on it never reach in-degree0,order.size() < numCourses, and{}is returned. - Deep chains of 2000 courses: the method is iterative, so there is no recursion-depth risk.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { vector<vector<int>> adj(numCourses); vector<int> indeg(numCourses, 0); for (const auto& pre : prerequisites) { adj[pre[1]].push_back(pre[0]); indeg[pre[0]]++; }
vector<int> order; // also used as the BFS queue order.reserve(numCourses); for (int c = 0; c < numCourses; c++) if (indeg[c] == 0) order.push_back(c);
for (size_t head = 0; head < order.size(); head++) { for (int v : adj[order[head]]) if (--indeg[v] == 0) order.push_back(v); }
if ((int)order.size() < numCourses) return {}; return order; }};class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { List<List<Integer>> adj = new ArrayList<>(); for (int c = 0; c < numCourses; c++) adj.add(new ArrayList<>()); int[] indeg = new int[numCourses]; for (int[] pre : prerequisites) { adj.get(pre[1]).add(pre[0]); indeg[pre[0]]++; }
int[] order = new int[numCourses]; // also used as the BFS queue int tail = 0; for (int c = 0; c < numCourses; c++) if (indeg[c] == 0) order[tail++] = c;
for (int head = 0; head < tail; head++) { for (int v : adj.get(order[head])) if (--indeg[v] == 0) order[tail++] = v; }
return tail < numCourses ? new int[0] : order; }}class Solution: def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]: adj = [[] for _ in range(numCourses)] indeg = [0] * numCourses for a, b in prerequisites: adj[b].append(a) indeg[a] += 1
order = [c for c in range(numCourses) if indeg[c] == 0] # also used as the BFS queue head = 0 while head < len(order): for v in adj[order[head]]: indeg[v] -= 1 if indeg[v] == 0: order.append(v) head += 1
return order if len(order) == numCourses else []Give it a try first
Attempt the problem on LeetCode — the code will still be here.
