Course Schedule

Can all courses be finished given prerequisites? Cycle detection via 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 true iff all courses can be taken.

Examples#

  • numCourses = 2, prerequisites = [[1, 0]]true
  • numCourses = 2, prerequisites = [[1, 0], [0, 1]]false

Constraints#

  • 1 <= numCourses <= 2000.

Approach#

Kahn’s BFS. Build adjacency list and indegrees. Enqueue all 0-indegree nodes; pop, decrement neighbors, enqueue when neighbor hits 0. Return true iff every node was processed.

Solution#

Course Schedule
class Solution {
public:
bool canFinish(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);
int taken = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
++taken;
for (int v : adj[u]) if (--indeg[v] == 0) q.push(v);
}
return taken == n;
}
};

Editorial#

Kahn’s algorithm detects cycles: a cycle prevents some node’s indegree from reaching 0, so taken < n at the end.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.