Coding problem · Medium · Graphs

Course Schedule

Medium Algorithms & data structures Seen at Amazon, Google, Meta, Uber

There are numCourses courses labelled 0..numCourses-1. prerequisites[i] = [a, b] means you must take b before a. Return true if you can finish all courses.

Example 1

Input: numCourses = 2, prerequisites = [[1,0]]
Output: true

Example 2

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: The two courses depend on each other.

Hints

Hint 1

This is cycle detection in a directed graph.

Hint 2

Kahn's algorithm: repeatedly take courses with no remaining prerequisites (in-degree 0).

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(V + E) · Space O(V + E)

Kahn's topological sort: count in-degrees, start a queue with all courses that have none, and repeatedly 'take' a course, decrementing its dependants' in-degrees. If every course gets taken there is no cycle.

Reference solution

function canFinish(numCourses, prerequisites) {
  const indeg = new Array(numCourses).fill(0);
  const next = Array.from({ length: numCourses }, () => []);
  for (const [a, b] of prerequisites) { next[b].push(a); indeg[a]++; }
  const queue = [];
  indeg.forEach((d, i) => d === 0 && queue.push(i));
  let taken = 0;
  while (queue.length) {
    const c = queue.shift();
    taken++;
    for (const d of next[c]) if (--indeg[d] === 0) queue.push(d);
  }
  return taken === numCourses;
}

Follow-up questions

  • Return a valid order (Course Schedule II).