207. Course Schedule
Asked at 43Amazon75Apple72Meta67Microsoft52Google51Bloomberg43TikTok83Snowflake73Anduril72Salesforce52Infosys30Nordstrom100Zenefits100Yelp94Coupang87Swiggy77ByteDance75Cruise72BitGo68LiveRamp67CrowdStrike65Akamai64Uber63Zomato62Roblox62MongoDB61Cloudflare60IXL57Oracle55Snap55Walmart Labs53eBay53Flipkart52Tesla52Booking.com50Nvidia48Adobe44Zoho42PayPal42DoorDash41Cisco37LinkedIn27Goldman Sachs21
Problem
There are numCourses courses, 0 to n − 1. prerequisites[i] = [a, b] means course b must be taken before course a. Decide whether all courses can be finished.
Example: numCourses = 2, prerequisites = [[1,0]] → true; [[1,0],[0,1]] → false
Constraints: up to 2000 courses and 5000 prerequisites.
Courses are a directed graph; finishable ⇔ no cycle. Kahn's algorithm: repeatedly take nodes with in-degree 0; if all n get taken, there's no cycle.
[[1,0]] edge 0 -> 1 indeg 0:0 1:1
queue [0] -> take 0 -> indeg[1]=0 -> take 1 taken 2 == n ✓
[[1,0],[0,1]] indeg 1,1 -> queue empty -> taken 0 < 2 ✗ cycle
Complexity: O(V + E).
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
g, indeg = defaultdict(list), [0] * numCourses
for a, b in prerequisites:
g[b].append(a)
indeg[a] += 1
q = deque(i for i in range(numCourses) if indeg[i] == 0)
taken = 0
while q:
u = q.popleft()
taken += 1
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return taken == numCourses
assert Solution().canFinish(2, [[1, 0]]) is True
assert Solution().canFinish(2, [[1, 0], [0, 1]]) is False
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < numCourses; i++) g.add(new ArrayList<>());
int[] indeg = new int[numCourses];
for (int[] p : prerequisites) { g.get(p[1]).add(p[0]); indeg[p[0]]++; }
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) q.add(i);
int taken = 0;
while (!q.isEmpty()) {
int u = q.poll();
taken++;
for (int v : g.get(u)) if (--indeg[v] == 0) q.add(v);
}
return taken == numCourses;
}
}
func canFinish(numCourses int, prerequisites [][]int) bool {
g, indeg := make([][]int, numCourses), make([]int, numCourses)
for _, p := range prerequisites {
g[p[1]] = append(g[p[1]], p[0])
indeg[p[0]]++
}
q := []int{}
for i, d := range indeg {
if d == 0 {
q = append(q, i)
}
}
taken := 0
for len(q) > 0 { // Kahn's algorithm: a cycle leaves courses with indegree > 0
u := q[0]
q = q[1:]
taken++
for _, v := range g[u] {
if indeg[v]--; indeg[v] == 0 {
q = append(q, v)
}
}
}
return taken == numCourses
}