Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in JavaScript: Topological Sort (Kahn's Algorithm)

Practice O(V + E) Read the full explanation

You get numCourses courses, numbered 0 to numCourses - 1. You also get an array prerequisites of pairs [a, b]. A pair means you must finish course b before you start course a.

Return true if you can take all the courses in some order. If you can't, return false.

 

Example 1:

Input: numCourses = 5, prerequisites = [[1, 0], [2, 1], [4, 3], [4, 2]]
Output: true
Explanation: Each arrow goes from a course to a course that needs it:
    0 → 1 → 2 → 4
            3 → 4
Course 4 needs both 2 and 3.
Taking the courses in number order, from 0 to 4, works.

Example 2:

Input: numCourses = 4, prerequisites = [[1, 0], [2, 1], [3, 2], [1, 3]]
Output: false
Explanation: The arrows 1 → 2 → 3 → 1 form a loop.
Course 1 waits for course 3.
Course 3 waits for course 2.
Course 2 waits for course 1.
Course 0 is fine, but the other three can never start.

Example 3:

Input: numCourses = 3, prerequisites = []
Output: true
Explanation: No course has a prerequisite, so any order works.

 

Constraints:

  • 1 to 100,000 courses.
  • Up to 100,000 pairs.
  • Both courses in a pair are valid course numbers.
  • The two courses in a pair are different.
  • No pair appears twice.
STEP 1 OF 16
    Ctrl + Enter to check

    JAVASCRIPT · GRAPHS

    Course Schedule in JavaScript, explained

    Problem overview

    The method canFinish(numCourses, prerequisites) gets the number of courses, labeled 0 to numCourses - 1, and an array of pairs. A pair [a, b] means course b must be taken before course a. The method returns true if every course can be taken in some order that respects all the pairs, and false otherwise.

    With numCourses = 2 and prerequisites = [[1, 0]], take course 0 and then course 1, so the answer is true. With [[1, 0], [0, 1]], each course waits for the other, so neither can ever start and the answer is false.

    Approach: take courses whose prerequisites are done

    Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that needs it. An order of all the courses in which every arrow points forward is a topological order. All courses can be finished exactly when such an order exists, which happens exactly when the arrows contain no cycle.

    Kahn's algorithm builds the order greedily:

    1. Count, for every course, how many prerequisites it still waits for. This is its in-degree, the number of arrows pointing into it.
    2. Put every course with a count of 0 into a queue. Those can be taken now.
    3. Take the courses from the queue one at a time. Taking a course removes its outgoing arrows: each course that waited for it has one prerequisite fewer. When a count reaches 0, that course joins the queue.
    4. If all courses were taken, the answer is true. Courses on a cycle never reach a count of 0, and neither does any course that needs one of them, so the number taken falls short.

    The example numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] produces these structures. The first line is the graph (position b lists the courses waiting for b) and the second is the starting in-degree:

    graph:    [[1,2],[3],[3],[]]
    inDegree: [0,1,1,2]
    

    Only course 0 starts in the queue. Taking each course in turn gives:

    took 0: inDegree [0,0,0,2]  queue [0,1,2]
    took 1: inDegree [0,0,0,1]  queue [0,1,2]
    took 2: inDegree [0,0,0,0]  queue [0,1,2,3]
    took 3: inDegree [0,0,0,0]  queue [0,1,2,3]
    

    Course 3 joins the queue only after both of its prerequisites, 1 and 2, are taken. All four courses were taken, so the answer is true.

    Step by step

    1. Build graph with Array.from({length: numCourses}, () => []). The callback runs once per course, so every course gets its own empty array. graph[b] will list the courses that wait for b.
    2. Build inDegree, an array of zeros. inDegree[a] counts the prerequisites of course a that are not taken yet.
    3. Loop over prerequisites with for...of. Each pair becomes one arrow.
    4. Record the arrow: push prereq[0] onto graph[prereq[1]], because the course in position 1 comes first.
    5. Count the dependency: add 1 to inDegree[prereq[0]].
    6. Create queue as an empty array for the courses that can be taken now.
    7. Scan every course with a for loop and push the ones whose inDegree is 0. If there are none, every course waits for another one.
    8. Start taken at 0. It counts the courses taken and doubles as the index of the next course to take from the queue. Nothing is ever removed from the array: the entries before taken are already taken.
    9. Loop while taken < queue.length. The queue grows while the loop runs, and the loop ends when every course that joined it has been taken.
    10. Read queue[taken] into course, then add 1 to taken.
    11. Visit the courses waiting for it: loop over graph[course], subtract 1 from each inDegree[nextCourse], and push nextCourse onto the queue when the count reaches 0. A count reaches 0 only once, so each course enters the queue at most once.
    12. Return taken === numCourses.

    The solution in JavaScript

    class Solution {
        canFinish(numCourses, prerequisites) {
            const graph = Array.from({length: numCourses}, () => []);
            const inDegree = new Array(numCourses).fill(0);
            for (const prereq of prerequisites) {
                graph[prereq[1]].push(prereq[0]);
                inDegree[prereq[0]]++;
            }
            const queue = [];
            for (let course = 0; course < numCourses; course++) {
                if (inDegree[course] === 0) {
                    queue.push(course);
                }
            }
            let taken = 0;
            while (taken < queue.length) {
                const course = queue[taken];
                taken++;
                for (const nextCourse of graph[course]) {
                    inDegree[nextCourse]--;
                    if (inDegree[nextCourse] === 0) {
                        queue.push(nextCourse);
                    }
                }
            }
            return taken === numCourses;
        }
    }
    

    Some JavaScript details worth knowing:

    • Array.from versus fill for the graph. new Array(3).fill([]) puts the same array at all three positions. After sh[0].push(1) on such an array, printing it with JSON.stringify gives [[1],[1],[1]]. Array.from with a callback runs the callback per index and builds separate arrays. For inDegree, fill(0) is fine because numbers are copied by value.
    • A queue without shift. JavaScript has no built-in queue type. Calling queue.shift() works, but it removes the first element and moves the others down. Reading with an index, as here, keeps every step constant-time and leaves the queue intact, which is why taken can be compared with numCourses at the end.
    • for...of versus for...in. for (const nextCourse of graph[course]) gives the values. for...in would give the indices as strings.
    • ++ and -- on array elements. inDegree[nextCourse]-- changes the element in place.

    Complexity

    Time: O(V + E), with V courses and E pairs. Building the graph touches each pair once. Each course enters the queue at most once, and when it is taken its list is scanned once, so every arrow is looked at once overall.

    Space: O(V + E) for the graph, the in-degree array and the queue. The adjacency lists hold one entry per pair.

    Edge cases and common mistakes

    • No prerequisites. With numCourses = 3 and prerequisites = [], every course starts in the queue and the answer is true.
    • Reversed arrows. In [a, b], b comes first. Building graph[a] instead of graph[b] would turn the problem around and count the wrong in-degrees.
    • Cycles away from the start. With numCourses = 4 and [[1, 0], [2, 1], [1, 2]], course 0 is free, but courses 1 and 2 wait for each other and course 3 is free too. Only 0 and 3 are taken, so the answer is false. Checking only that some course starts at 0 is not enough.
    • Cycle of every course. With [[1, 0], [2, 1], [0, 2]] and 3 courses, nothing has an in-degree of 0 and the queue starts empty, so the loop never runs and 0 === 3 is false.
    • Returning true when the queue empties. The queue always empties eventually. The answer depends on whether all courses went through it.
    • Recursion depth. A recursive depth-first search for cycles on a chain of 100,000 courses can overflow the call stack. Kahn's algorithm uses loops only: a chain of 100,000 courses returns true.

    Testing

    • numCourses = 2, prerequisites = [[1, 0]] gives true.
    • numCourses = 2, prerequisites = [[1, 0], [0, 1]] gives false.
    • numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] gives true.
    • numCourses = 3, prerequisites = [[1, 0], [2, 1], [0, 2]] gives false.
    • numCourses = 4, prerequisites = [[1, 0], [2, 1], [1, 2]] gives false.
    • numCourses = 1, prerequisites = [] gives true.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free