17. Course Schedule
mediumAsked at AutodeskDecide if you can finish all courses given prerequisite pairs that form a directed graph.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
There are numCourses labeled from 0 to numCourses-1. You are given prerequisite pairs [a, b] meaning you must take b before a. Return true if you can finish all courses, i.e., the directed prerequisite graph has no cycle.
Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= 5000
Examples
Example 1
numCourses=2, prereqs=[[1,0]]trueExample 2
numCourses=2, prereqs=[[1,0],[0,1]]falseApproaches
1. DFS color marking
Color nodes white/gray/black; gray reentry means a cycle.
- Time
- O(V+E)
- Space
- O(V+E)
function dfs(u){ if (color[u]===1) return false; if (color[u]===2) return true; color[u]=1; for (v of adj[u]) if (!dfs(v)) return false; color[u]=2; return true; }Tradeoff:
2. Kahn's BFS topological sort
Compute indegrees, push zero-indegree nodes onto a queue, and pop while decrementing neighbors. If you pop all V nodes there's no cycle.
- Time
- O(V+E)
- Space
- O(V+E)
function canFinish(n, prereqs) {
const adj = Array.from({length: n}, () => []);
const indeg = new Array(n).fill(0);
for (const [a, b] of prereqs) { adj[b].push(a); indeg[a]++; }
const q = [];
for (let i = 0; i < n; i++) if (indeg[i] === 0) q.push(i);
let taken = 0;
while (q.length) {
const u = q.shift();
taken++;
for (const v of adj[u]) if (--indeg[v] === 0) q.push(v);
}
return taken === n;
}Tradeoff:
Autodesk-specific tips
Topo-order reasoning maps directly onto Autodesk's dependency DAGs in parametric modeling (Fusion timeline, Revit family graph).
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Course Schedule and other Autodesk interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →