Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in C++: Topological Sort with Kahn's Algorithm

Practice O(V + E) Read the full explanation

You get numCourses courses, numbered 0 to numCourses - 1. You also get a vector 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

    C++ · GRAPHS

    Course Schedule in C++, explained

    Problem overview

    The method canFinish receives numCourses and a vector<vector<int>> named prerequisites. A pair [a, b] means course b must be taken before course a. It returns true if every course can be finished and false otherwise.

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

    Draw each pair [a, b] as an arrow from b to a. All courses can be finished exactly when these arrows form no cycle, that is, when there is an order of the courses in which every arrow points forward (a topological order).

    Approach: take free courses and remove their arrows

    A course with no remaining prerequisites can be taken now. Taking it removes its arrows, which may free other courses. This is Kahn's algorithm:

    1. Count, for every course, how many prerequisites it has (its in-degree).
    2. Put every course with count 0 in a queue.
    3. Take a course from the queue. For each course that waits for it, lower the count by one, and queue it when the count reaches 0.
    4. Repeat until the queue is empty.

    Courses on a cycle never reach count 0, and neither does any course that needs one of them. So the answer is whether the number of courses taken equals numCourses.

    For example 3, numCourses = 4 and [[1, 0], [2, 0], [3, 1], [3, 2]], the in-degrees are 0, 1, 1, 2. Course 0 is the only free one, and the courses come out in the order 0, 1, 2, 3. Course 3 enters the queue only after both 1 and 2 were taken.

    With [[1, 0], [2, 1], [1, 2]] on three courses, only course 0 is free. Taking it lowers course 1's count from 2 to 1, which is not 0, so nothing else is freed. One course is taken out of three, and the answer is false.

    Step by step

    1. Create graph with numCourses empty inner vectors. graph[b] lists the courses waiting for course b.
    2. Create inDegree of zeros. inDegree[a] counts the prerequisites of course a not yet taken.
    3. Loop over the pairs by reference. For each, add prereq[0] to graph[prereq[1]], and increase inDegree[prereq[0]].
    4. Create the queue q and push every course whose count is 0. These are the possible starting points.
    5. Create taken, starting at 0.
    6. While the queue is not empty, read the front course, then pop it.
    7. Count it as taken.
    8. Visit the courses waiting for it. Subtract one from each one's in-degree, and push it when the count hits 0.
    9. Return taken == numCourses.

    The solution in C++

    class Solution {
    public:
        bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
            vector<vector<int>> graph(numCourses);
            vector<int> inDegree(numCourses, 0);
            for (auto& prereq : prerequisites) {
                graph[prereq[1]].push_back(prereq[0]);
                inDegree[prereq[0]]++;
            }
            queue<int> q;
            for (int course = 0; course < numCourses; course++) {
                if (inDegree[course] == 0) {
                    q.push(course);
                }
            }
            int taken = 0;
            while (!q.empty()) {
                int course = q.front();
                q.pop();
                taken++;
                for (int nextCourse : graph[course]) {
                    inDegree[nextCourse]--;
                    if (inDegree[nextCourse] == 0) {
                        q.push(nextCourse);
                    }
                }
            }
            return taken == numCourses;
        }
    };
    

    C++ details worth knowing:

    • Sized vectors. vector<vector<int>> graph(numCourses) creates that many empty inner vectors, so graph[b].push_back(a) is safe for any valid b.
    • auto& binds each pair by reference, avoiding a copy of a small vector per iteration. Reading prereq[0] and prereq[1] is valid because the constraints guarantee two numbers per pair.
    • front() and pop() are separate. std::queue::pop() returns nothing, so copy the front value first. Calling front() on an empty queue is undefined behaviour, which is why the loop tests !q.empty().
    • Naming the queue q. The type is already called queue.
    • Loop variable by value. for (int nextCourse : graph[course]) copies each int, which is cheap, and the loop only reads graph.
    • Stack safety. The algorithm uses a queue, not recursion, so a chain of 100,000 courses is fine: with each course requiring the previous one, canFinish returns true.

    Complexity

    Time: O(V + E) for V courses and E pairs. Building the graph looks at each pair once. Each course enters the queue at most once, because its count reaches 0 only once, and each pair is examined once when its first course is taken.

    Space: O(V + E). The adjacency lists hold E entries, and inDegree and the queue hold at most V.

    Edge cases and common mistakes

    • No prerequisites. Every course is free at the start, so all are taken and the answer is true.
    • Reversed arrows. In [a, b], b comes first. Putting a in graph[a] or increasing inDegree[b] answers a different question.
    • A cycle that doesn't include every course. With [[1, 0], [2, 1], [0, 2]] on 3 courses, nothing is free, so none is taken and the answer is false. A cycle somewhere is enough to fail, even if other courses are fine.
    • Checking only that the queue starts non-empty. Some courses can be free while others are stuck in a cycle. Compare the final count of taken courses.
    • Pushing a course twice. Push it when its count becomes exactly 0, not whenever the count is 0 or less.

    Testing

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