Course Schedule

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write canFinish(n, prerequisites). There are n courses numbered 0 to n − 1, and each pair [a, b] in prerequisites means course b must be taken before course a. Return true if every course can be taken, which is when the prerequisites form no cycle, and false if not. A course that requires itself is a cycle, and a pair may appear more than once. For example, canFinish(2, [[1, 0]]) is true, and canFinish(2, [[1, 0], [0, 1]]) is false. The checks include a chain of 100,000 courses, each needing the next, which is too deep for recursion.

Your code must pass

  • Returns true when the courses can be ordered
  • Returns false when the prerequisites form a cycle
  • Finds a cycle in one part of a larger plan
  • Handles courses with no prerequisites
  • Is fast enough for a chain of 100,000 courses