17. Course Schedule II
mediumAsked at GitLabReturn any valid course ordering that satisfies the prerequisite dependencies, or an empty list if the graph has a cycle.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given numCourses and prerequisite pairs [a, b] meaning b precedes a, return an order in which you can take all courses. If no order exists (cycle), return [].
Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= numCourses*(numCourses-1)
Examples
Example 1
numCourses=2, prerequisites=[[1,0]][0,1]Example 2
numCourses=4, prerequisites=[[1,0],[2,0],[3,1],[3,2]][0,1,2,3]Approaches
1. DFS post-order
DFS each node; on finish push to a list, then reverse. Detect cycles with gray markers.
- Time
- O(V+E)
- Space
- O(V+E)
const out=[]; const col=new Array(n).fill(0);
const dfs=u=>{ if (col[u]===1) return false; if (col[u]===2) return true;
col[u]=1; for (const v of g[u]) if (!dfs(v)) return false;
col[u]=2; out.push(u); return true; };
for (let i=0;i<n;i++) if (!dfs(i)) return [];
return out.reverse();Tradeoff:
2. Kahn's topological sort
Process zero-in-degree nodes via a queue, appending each to the result. If the result has all n nodes, return it; otherwise return [].
- Time
- O(V+E)
- Space
- O(V+E)
function findOrder(n, pre){
const g = Array.from({length:n}, () => []);
const inDeg = new Array(n).fill(0);
for (const [a, b] of pre){ g[b].push(a); inDeg[a]++; }
const q = [], order = [];
for (let i = 0; i < n; i++) if (inDeg[i] === 0) q.push(i);
while (q.length){
const u = q.shift();
order.push(u);
for (const v of g[u]) if (--inDeg[v] === 0) q.push(v);
}
return order.length === n ? order : [];
}Tradeoff:
GitLab-specific tips
GitLab will press you to articulate why Kahn's BFS naturally falls out of how their CI scheduler streams ready jobs onto a runner pool the instant their prerequisites land.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Course Schedule II and other GitLab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →