Start learning free

LESSON 285 OF 314 · GRAPHS

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

    RUST · GRAPHS

    Course Schedule in Rust, explained

    Problem overview

    The function can_finish receives num_courses, the number of courses (labelled 0 to num_courses - 1), and prerequisites, a vector of pairs [a, b]. A pair means that course b must be taken before course a. It returns true if all the courses can be finished and false otherwise.

    With 2 courses and [[1, 0]], take course 0 and then course 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]], the order 0, 1, 2, 3 respects every pair: true.

    Approach: take courses that have nothing left to wait for

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

    Kahn's algorithm builds the order step by step. Count the unmet prerequisites of each course, its in-degree. A course with count 0 can be taken now. Taking it removes its arrows, so each course that waited for it has one prerequisite fewer, and any that reach 0 become available. Keep going until nothing is available, and compare how many courses were taken with num_courses. Courses on a cycle wait for each other forever, so their counts never reach 0, and neither does the count of any course that needs one of them.

    Here is the third example. The graph lists, for each course, the courses that wait for it, and the in-degree list counts each course's prerequisites:

    graph=[[1, 2], [3], [3], []] in_degree=[0, 1, 1, 2]
    queue=[0]
    took 0: in_degree=[0, 0, 0, 2] queue=[1, 2] taken=1
    took 1: in_degree=[0, 0, 0, 1] queue=[2] taken=2
    took 2: in_degree=[0, 0, 0, 0] queue=[3] taken=3
    took 3: in_degree=[0, 0, 0, 0] queue=[] taken=4

    All 4 courses were taken, so the answer is true. For 3 courses with [[1, 0], [2, 1], [1, 2]], courses 1 and 2 form a cycle, and the run stops early:

    graph=[[1], [2], [1]] in_degree=[0, 2, 1]
    queue=[0]
    took 0: in_degree=[0, 1, 1] queue=[] taken=1

    Only 1 course out of 3 was taken, so the answer is false.

    Step by step

    1. Create graph, a Vec<Vec<usize>> with one empty vector per course. graph[b] will hold the courses that wait for b.
    2. Create in_degree, a vector of zeros. in_degree[a] will count the prerequisites of a.
    3. Loop over &prerequisites. The & borrows the vector instead of moving it.
    4. Add the arrow: push prereq[0] onto graph[prereq[1]], converting both with as usize.
    5. Count the prerequisite: add 1 to in_degree[prereq[0] as usize]. Rust has no ++.
    6. Create a VecDeque named queue for the courses that can be taken now.
    7. Loop over every course and push those with in_degree[course] == 0 onto the back of the queue.
    8. Start taken at 0.
    9. Loop while the queue isn't empty. Each course enters the queue at most once, so this runs at most num_courses times.
    10. Take the course at the front with pop_front().unwrap() and add 1 to taken. The unwrap is safe because the loop condition just checked that the queue has an element.
    11. Loop over the courses that wait for it, using the pattern &next_course over &graph[course].
    12. Subtract 1 from in_degree[next_course]: one of its prerequisites is done.
    13. If the count reaches 0, push next_course onto the queue.
    14. Return taken == num_courses as the last expression, without a semicolon.

    The solution in Rust

    use std::collections::VecDeque;
    
    impl Solution {
        fn can_finish(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool {
            let mut graph: Vec<Vec<usize>> = vec![Vec::new(); num_courses as usize];
            let mut in_degree = vec![0; num_courses as usize];
            for prereq in &prerequisites {
                graph[prereq[1] as usize].push(prereq[0] as usize);
                in_degree[prereq[0] as usize] += 1;
            }
            let mut queue: VecDeque<usize> = VecDeque::new();
            for course in 0..num_courses as usize {
                if in_degree[course] == 0 {
                    queue.push_back(course);
                }
            }
            let mut taken = 0;
            while !queue.is_empty() {
                let course = queue.pop_front().unwrap();
                taken += 1;
                for &next_course in &graph[course] {
                    in_degree[next_course] -= 1;
                    if in_degree[next_course] == 0 {
                        queue.push_back(next_course);
                    }
                }
            }
            taken == num_courses
        }
    }
    

    Rust details worth knowing:

    • vec![Vec::new(); k] clones its element. Every course gets its own empty vector, not one shared vector. That works because Vec implements Clone, and the annotation on graph tells the compiler what kind of vector is inside.
    • Index types. The input numbers are i32, but indexes must be usize, so each value taken from prerequisites is cast with as usize. The numbers pushed into graph are already usize, so the loop later needs no cast.
    • The type of taken. taken == num_courses compares with an i32, so Rust infers that taken is an i32 too. The vector in_degree has no stated element type, and with no other constraint Rust uses i32 for it as well.
    • for &next_course in &graph[course]. Iterating over a borrowed vector yields references, and the pattern &next_course copies the number out of each one. This also keeps graph borrowed only for reading, so the loop body is free to change in_degree and queue.
    • VecDeque. It is a double-ended queue in std::collections. push_back and pop_front both take constant time. A plain Vec would make removing from the front slow.
    • Final expression. taken == num_courses has no semicolon, so it is the bool that the function returns.

    Complexity

    Let V be the number of courses and E the number of pairs.

    Time: O(V + E). Building the graph looks at each pair once. Each course enters the queue at most once, and when it leaves, the loop looks at each of its outgoing arrows once, so each pair is processed once overall.

    Space: O(V + E). The graph holds one entry per pair plus one vector per course, and in_degree and the queue hold at most V numbers.

    Edge cases and common mistakes

    • No prerequisites. Every in-degree is 0, all courses go into the queue, and the answer is true. A single course with no pairs returns true as well.
    • Reading the pair backwards. In [a, b], course a is the one that waits. So a goes into graph[b], and it is in_degree[a] that grows.
    • A cycle that doesn't include every course. Course 0 can be taken in the cycle example above, yet the answer is false, because the count of taken courses, 1, is less than 3. Checking that the queue ever had a course in it is not enough.
    • No starting course. If every course has a prerequisite, the queue starts empty, taken stays 0, and the answer is false.
    • Recursive depth-first search. A recursive version can run out of call stack on a chain of 100,000 courses. The queue-based loop uses no recursion.
    • Stale counts. Subtract from in_degree only once per pair. The pairs are distinct, so each arrow is used exactly once.

    Testing

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