Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in TypeScript: 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

    TYPESCRIPT · GRAPHS

    Course Schedule in TypeScript, explained

    Problem overview

    There are numCourses courses labeled 0 to numCourses - 1. Each pair [a, b] in prerequisites means course b must be taken before course a. The method canFinish 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]], course 0 needs nothing and course 1 needs course 0, so the order 0, 1 works and the answer is true. With [[1, 0], [0, 1]] each course waits for the other, so neither can ever be taken and the answer is false.

    It helps to 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. Such an order exists exactly when the arrows contain no cycle, so the question is really "does this graph have a cycle?"

    Approach: take free courses and remove their arrows

    Think of how you would plan the courses by hand. Start with the courses that have no prerequisites. Taking one of them removes it as a requirement for others, and some of those may now be free. Keep going until nothing is free. If you took every course, the plan works. If some courses are left, each of them still waits for another one that was never taken, which can only happen when they wait on each other in a cycle, or on a course that does.

    This is Kahn's algorithm. It needs two things per course: the list of courses that wait for it, and the count of its prerequisites not yet taken, called the in-degree (the number of arrows pointing into the course). A course is free when its count reaches 0. Each pair is looked at a constant number of times, so the work is O(V + E) for V courses and E pairs, which fits the limits of 100,000 each.

    A depth-first search that looks for cycles also works. Kahn's algorithm avoids recursion, which matters here: a chain of 100,000 courses would make a recursive search go 100,000 calls deep.

    Step by step

    1. Build the graph. graph[b] holds the courses that wait for course b. Array.from({length: numCourses}, () => []) runs the arrow function once per course, so each course gets its own array.
    2. Create inDegree, an array of zeros. inDegree[a] counts the prerequisites of course a that are not taken yet.
    3. Loop over the pairs. For each pair, push prereq[0] onto graph[prereq[1]] (course prereq[0] waits for prereq[1]) and add 1 to inDegree[prereq[0]].
    4. Create the queue of courses that can be taken now, and fill it with every course whose in-degree is 0. If there are none, every course waits for another, and nothing can start.
    5. Keep a counter, taken. It counts the courses taken so far and is also the position of the next course to take in queue. Nothing is ever removed from the queue: reading by index avoids shift(), which moves every remaining element.
    6. Loop while taken < queue.length. The queue grows as courses become free, and the loop ends when every course that joined it has been taken.
    7. Take a course: read queue[taken] and increment taken.
    8. Release the courses that wait for it. For each nextCourse in graph[course], decrement its in-degree. When it reaches 0 its last prerequisite has just been taken, so push it onto the queue. A count hits 0 only once, so each course enters the queue at most once.
    9. Return taken === numCourses. Courses on a cycle never reach 0, and neither does any course that needs one of them, so they are never taken.

    The solution in TypeScript

    class Solution {
        canFinish(numCourses: number, prerequisites: number[][]): boolean {
            const graph: number[][] = Array.from({length: numCourses}, () => []);
            const inDegree: number[] = new Array(numCourses).fill(0);
            for (const prereq of prerequisites) {
                graph[prereq[1]].push(prereq[0]);
                inDegree[prereq[0]]++;
            }
            const queue: number[] = [];
            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;
        }
    }
    

    For the third example, numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], only course 0 starts free. Taking it frees 1 and 2, and taking those frees 3. The final queue is [0, 1, 2, 3], taken is 4, and the method returns true. For the cyclic example [[1, 0], [0, 1]] the queue stays empty, taken is 0 and the result is false. With numCourses = 3 and [[1, 0], [2, 1], [1, 2]], course 0 is taken, but courses 1 and 2 wait for each other: the queue is [0], taken is 1 and the result is false.

    Some TypeScript details:

    • Why not new Array(numCourses).fill([])? fill stores the same array object in every slot. After shared[0].push(7) on such an array of three slots, it prints as [[7],[7],[7]]. With Array.from(..., () => []) the same push gives [[7],[],[]]. Filling with 0 is fine because numbers are copied by value.
    • Types are erased. number[][] checks nothing at run time. The compiler uses it to know that graph[b] is an array of numbers.
    • === in the checks. inDegree[course] === 0 and taken === numCourses compare numbers without any conversion.
    • for...of versus for. for...of reads the values, which is what the pair and neighbour loops need. The loop over courses needs the index itself, so it uses a counter.
    • Reading a growing array. The while condition re-reads queue.length on every turn, so the pushes made inside the loop extend it.

    Complexity

    Time: O(V + E). Building the graph touches each pair once. Each course enters the queue at most once and is taken once, and when it is taken its list of waiting courses is scanned once. Over the whole run, every pair is scanned exactly once.

    Space: O(V + E). graph holds one array per course and one entry per pair, and inDegree and queue hold at most one number per course.

    Edge cases and common mistakes

    • No prerequisites. canFinish(3, []) returns true: all three courses start in the queue, and taken reaches 3.
    • A single course. canFinish(1, []) returns true.
    • Swapping the pair. The pair [a, b] means b comes first. Using prereq[0] as the key of graph and incrementing inDegree[prereq[1]] reverses every arrow. It still answers the cycle question correctly, but the order it describes is backwards, so check the direction when you extend the code.
    • Counting the wrong thing at the end. Returning whether queue is empty, or checking only the courses that started free, misses courses stuck behind a cycle. Compare the number of courses taken with numCourses.
    • Using shift() for the queue. It works, but it moves every remaining element, so a long queue gets slow. The index taken avoids that.
    • Cycles that don't touch every course. In the 3-course example above, course 0 is fine and the answer is still false: one cycle anywhere is enough.
    • A long chain. With 100,000 courses in a line, [i, i - 1] for every i from 1 to 99999, the method returns true and the queue ends up with all 100,000 courses.

    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], [1, 2]] gives false.
    • numCourses = 3, prerequisites = [] gives true.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free