Course Schedule II

Return a valid course order — Kahn's BFS topological sort.

Medium
Time O(V + E) Space O(V + E)
LeetCode
3 min read
topological-sort graph

Problem#

Given numCourses and prerequisites [course, prereq], return any valid course-taking order, or [] if impossible.

Examples#

  • numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]][0,2,1,3] (or similar)

Constraints#

  • 1 <= numCourses <= 2000.

Approach#

Same Kahn’s BFS as Course Schedule, but accumulate the output order.

Solution#

Course Schedule II
class Solution {
public:
vector<int> findOrder(int n, vector<vector<int>>& prerequisites) {
vector<vector<int>> adj(n);
vector<int> indeg(n, 0);
for (auto& p : prerequisites) {
adj[p[1]].push_back(p[0]);
++indeg[p[0]];
}
queue<int> q;
for (int i = 0; i < n; ++i) if (indeg[i] == 0) q.push(i);
vector<int> out;
while (!q.empty()) {
int u = q.front(); q.pop();
out.push_back(u);
for (int v : adj[u]) if (--indeg[v] == 0) q.push(v);
}
return (int)out.size() == n ? out : vector<int>{};
}
};

Editorial#

Cycle detection by mismatched output length. Output order may vary based on tie-breaking.

Complexity#

  • Time: O(V + E).
  • Space: O(V + E).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.