Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in C#: Topological Sort with a Queue

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 18
    Ctrl + Enter to check

    C# · GRAPHS

    Course Schedule in C#, explained

    Problem overview

    The method CanFinish receives numCourses, the number of courses (labelled 0 to numCourses - 1), and prerequisites, an int[][] of pairs [a, b]. A pair means course b must be taken before course a. It returns true if all the courses can be finished and false otherwise.

    With numCourses = 2 and [[1,0]], take 0, then 1: true. With [[1,0],[0,1]], each course waits for the other, so neither can start: false. With 4 courses and [[1,0],[2,0],[3,1],[3,2]], course 0 needs nothing, courses 1 and 2 need 0, and course 3 needs both 1 and 2, so the order 0, 1, 2, 3 works.

    Approach: take courses that have no prerequisites left

    Draw each pair as an arrow from the course to take first to the course that needs it. The courses can all be finished exactly when there is an order of them in which every arrow points forward (a topological order), and that is possible exactly when the arrows contain no cycle.

    This lesson builds such an order with Kahn's algorithm:

    1. Count, for every course, how many of its prerequisites are not taken yet. This is its in-degree, the number of arrows pointing into it.
    2. Put the courses with count 0 in a queue: they can be taken now.
    3. Take a course from the queue. For each course that was waiting for it, lower its count by one. If a count reaches 0, that course is free: add it to the queue.
    4. Repeat until the queue is empty. If all the courses were taken, the answer is true.

    Courses on a cycle wait for each other, so their counts never reach 0 and they are never taken. Neither is any course that needs one of them. So the number of courses taken falls short of numCourses exactly when a cycle exists.

    Step by step

    1. Create graph, a List<List<int>>. graph[b] will hold the courses that wait for course b.
    2. Add one empty list per course in a loop from 0 to numCourses - 1. There is no one-line way to build a list of separate lists, so each new List<int>() is added on its own.
    3. Create inDegree, an int[] of length numCourses. It starts with zeros, which is the right start.
    4. Read the pairs with foreach (int[] prereq in prerequisites). For each, add prereq[0] to graph[prereq[1]] and increase inDegree[prereq[0]]. After the loop, inDegree[a] is the number of pairs whose first number is a.
    5. Fill the queue. Create a Queue<int> and Enqueue every course whose in-degree is 0. These are where any valid order can start.
    6. Count the courses taken with an int taken that starts at 0.
    7. Loop while queue.Count > 0. Dequeue a course, add 1 to taken, and go through graph[course]. For each nextCourse, subtract 1 from its in-degree, and if it reaches 0, Enqueue it. A count reaches 0 only once, so each course enters the queue at most once.
    8. Return taken == numCourses.

    For the 4-course example the setup gives this:

    inDegree=[0,1,1,2]
    0 -> [1,2]
    1 -> [3]
    2 -> [3]
    3 -> []
    

    Only course 0 starts in the queue. Taking it frees courses 1 and 2. Taking those, in turn, lowers the in-degree of 3 to 1 and then to 0. The courses come out in the order 0, 1, 2, 3, so taken is 4 and the method returns true.

    The solution in C#

    class Solution {
        public bool CanFinish(int numCourses, int[][] prerequisites) {
            List<List<int>> graph = new List<List<int>>();
            for (int i = 0; i < numCourses; i++) {
                graph.Add(new List<int>());
            }
            int[] inDegree = new int[numCourses];
            foreach (int[] prereq in prerequisites) {
                graph[prereq[1]].Add(prereq[0]);
                inDegree[prereq[0]]++;
            }
            Queue<int> queue = new Queue<int>();
            for (int course = 0; course < numCourses; course++) {
                if (inDegree[course] == 0) {
                    queue.Enqueue(course);
                }
            }
            int taken = 0;
            while (queue.Count > 0) {
                int course = queue.Dequeue();
                taken++;
                foreach (int nextCourse in graph[course]) {
                    inDegree[nextCourse]--;
                    if (inDegree[nextCourse] == 0) {
                        queue.Enqueue(nextCourse);
                    }
                }
            }
            return taken == numCourses;
        }
    }
    

    The C# details worth knowing:

    • List<T> and Queue<T> live in System.Collections.Generic. In a file of your own, add using System.Collections.Generic; at the top.
    • Queue members. Enqueue adds at the back, Dequeue removes from the front, and Count is a property, written without parentheses. A List<T> also uses Count, while arrays use Length.
    • Two variables named course. The first lives only inside the for loop, and the second inside the while loop. C# allows this because their scopes don't overlap.
    • Array elements start at zero. new int[numCourses] is filled with 0, which is why inDegree needs no initialising loop.

    Complexity

    Let V be numCourses and E the number of pairs.

    Time: O(V + E). Building the graph takes one pass over the pairs plus V list creations. Each course enters the queue at most once, and when it leaves, its list is scanned once, so every pair is looked at one time in total.

    Space: O(V + E) for the adjacency lists, the in-degree array and the queue.

    Edge cases and common mistakes

    • No prerequisites. Every in-degree is 0, all the courses enter the queue, and the answer is true. For numCourses = 5 and an empty array it returns true.
    • Every course waits for another. The queue starts empty, taken stays 0 and the answer is false.
    • A cycle in part of the graph. With 3 courses and [[1,0],[2,1],[1,2]], course 0 is taken, but courses 1 and 2 wait for each other, so only 1 of 3 courses is taken and the result is false.
    • Mixing up the pair. prereq[1] is the course to take first and prereq[0] the one that waits. Keep the same direction in the graph and in the in-degrees, or the counts won't match the lists they are lowered through.
    • Enqueuing more than once. Enqueue a course only when its count reaches exactly 0, not whenever it is lower.
    • Using recursion. A recursive search over a long chain of 100,000 courses risks a stack overflow. The queue-based version has no such limit.

    Testing

    • 2, [[1,0]] gives true.
    • 2, [[1,0],[0,1]] gives false.
    • 4, [[1,0],[2,0],[3,1],[3,2]] gives true.
    • 3, [[1,0],[2,1],[1,2]] gives false.
    • 1 with no pairs gives true.
    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