Skip to main content
45

Course Schedule

Mediumgraphstopological sort

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:GraphsRead the beginner guide

There are numCourses courses, numbered 0 to numCourses - 1. Each pair [a, b] in prerequisites means you must take course b before course a.

Return true if you can finish every course, otherwise false.

Understand the problem

  • A prerequisite is a course you must complete before another one. [1, 0] means "to take course 1, first take course 0".
  • You can take courses in any order you like, as long as every prerequisite comes first.
  • The only way to get stuck is a circular requirement: courses that (directly or through a chain) each wait for the other.

Example 1

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

Take 0, then 1.

Example 2

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

1 needs 0 first, and 0 needs 1 first. Neither can ever start.

Example 3

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

Take 0; that unlocks 1 and 2; once both are done, take 3.

Constraints

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • All pairs are unique.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Repeatedly take any course whose prerequisites are all done, unlocking others as you go; if you manage to take every course, there was no circular dependency.

    It's a graph question

    Draw each course as a node, and each prerequisite [a, b] as an arrow b → a ("b unlocks a"). This is a directed graph: the arrows only go one way.

    Loading diagram...

    That's Example 3: 0 unlocks 1 and 2, which both unlock 3.

    You get stuck exactly when the arrows form a cycle, like 0 → 1 → 0: every course in the circle waits for another one in the circle, so none of them can start. So the question is really: does this directed graph have a cycle?

    The key insight: take what's free (Kahn's algorithm)

    Give each course an in-degree: the number of prerequisites it's still waiting on (the number of arrows pointing into it).

    1. Build, for each course, the list of courses it unlocks, and every course's in-degree.
    2. Put every course with in-degree 0 (nothing blocking it) in a queue.
    3. Repeatedly take a course from the queue and count it as taken. For each course it unlocks, lower that course's in-degree by 1. If it reaches 0, it's now free: add it to the queue.
    4. When the queue is empty, check: did you take all numCourses courses?

    Courses on a cycle are always waiting on each other, so their in-degree never reaches 0, and they're never taken. If anything is left over, there's a cycle.

    This process of ordering tasks so every dependency comes first is called a topological sort.

    Step by step

    Example 3: numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]].

    Starting in-degrees: 0 → 0, 1 → 1, 2 → 1, 3 → 2. Queue: [0].

    TakeTaken so farUnlocks: in-degree changeQueue after
    011: 1 → 0 ✅, 2: 1 → 0 ✅[1, 2]
    123: 2 → 1[2]
    233: 1 → 0 ✅[3]
    34nothing[]

    Taken 4 out of 4: true.

    In Example 2, both courses start with in-degree 1, so the queue starts empty, nothing is ever taken, and 0 ≠ 2: false.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With V courses and E prerequisites:

    • Time: O(V + E). Each course is taken once, and each arrow is followed once.
    • Memory: O(V + E) for the lists and the queue.

    Common mistakes

    • Drawing the arrows backward. [a, b] means b comes first: the arrow goes b → a. (Backward arrows still detect cycles correctly, but get confusing fast, and give the reverse order in Course Schedule II.)
    • Only checking direct pairs like [0, 1] and [1, 0]. Cycles can be long: 0 → 1 → 2 → 0.
    • Forgetting courses with no prerequisites at all. They start with in-degree 0 and must go in the queue.

    Going deeper

    • DFS with three colors also finds cycles: mark each course "unvisited", "in progress" (on the current DFS path) or "done". Reaching an "in progress" course means you've walked in a circle.
    • Course Schedule II asks for an actual order to take the courses. With Kahn's algorithm you already have it: it's the order courses come out of the queue.

    Reference solution

    js
    /**
     * @param {number} numCourses
     * @param {number[][]} prerequisites
     * @return {boolean}
     */
    export default function canFinish(numCourses, prerequisites) {
      // unlocks[b] = the courses that need b. inDegree[a] = how many prerequisites a still waits on.
      const unlocks = Array.from({ length: numCourses }, () => [])
      const inDegree = new Array(numCourses).fill(0)
      for (const [course, required] of prerequisites) {
        unlocks[required].push(course)
        inDegree[course]++
      }
    
      // Courses with nothing blocking them can be taken right away.
      const queue = []
      for (let course = 0; course < numCourses; course++) {
        if (inDegree[course] === 0) queue.push(course)
      }
      let taken = 0
      // Read the array as a queue with an index (shift() would be slow).
      for (let i = 0; i < queue.length; i++) {
        taken++ // take the next free course
        for (const next of unlocks[queue[i]]) {
          inDegree[next]-- // one less prerequisite to wait for
          if (inDegree[next] === 0) queue.push(next) // all done: it's free now
        }
      }
      // Courses stuck in a cycle never become free, so they're never taken.
      return taken === numCourses
    }
    ts
    export default function canFinish(numCourses: number, prerequisites: number[][]): boolean {
      // unlocks[b] = the courses that need b. inDegree[a] = how many prerequisites a still waits on.
      const unlocks: number[][] = Array.from({ length: numCourses }, () => [])
      const inDegree = new Array<number>(numCourses).fill(0)
      for (const [course, required] of prerequisites) {
        unlocks[required].push(course)
        inDegree[course]++
      }
    
      // Courses with nothing blocking them can be taken right away.
      const queue: number[] = []
      for (let course = 0; course < numCourses; course++) {
        if (inDegree[course] === 0) queue.push(course)
      }
      let taken = 0
      // Read the array as a queue with an index (shift() would be slow).
      for (let i = 0; i < queue.length; i++) {
        taken++ // take the next free course
        for (const next of unlocks[queue[i]]) {
          inDegree[next]-- // one less prerequisite to wait for
          if (inDegree[next] === 0) queue.push(next) // all done: it's free now
        }
      }
      // Courses stuck in a cycle never become free, so they're never taken.
      return taken === numCourses
    }
    python
    from collections import deque
    
    
    def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool:
        # unlocks[b] = the courses that need b. in_degree[a] = how many prerequisites a still waits on.
        unlocks = [[] for _ in range(num_courses)]
        in_degree = [0] * num_courses
        for course, required in prerequisites:
            unlocks[required].append(course)
            in_degree[course] += 1
    
        # Courses with nothing blocking them can be taken right away.
        queue = deque(course for course in range(num_courses) if in_degree[course] == 0)
        taken = 0
        while queue:
            taken += 1  # take the next free course
            for nxt in unlocks[queue.popleft()]:
                in_degree[nxt] -= 1  # one less prerequisite to wait for
                if in_degree[nxt] == 0:  # all done: it's free now
                    queue.append(nxt)
        # Courses stuck in a cycle never become free, so they're never taken.
        return taken == num_courses