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
- Create
graph, aVec<Vec<usize>>with one empty vector per course.graph[b]will hold the courses that wait forb. - Create
in_degree, a vector of zeros.in_degree[a]will count the prerequisites ofa. - Loop over
&prerequisites. The&borrows the vector instead of moving it. - Add the arrow: push
prereq[0]ontograph[prereq[1]], converting both withas usize. - Count the prerequisite: add 1 to
in_degree[prereq[0] as usize]. Rust has no++. - Create a
VecDequenamedqueuefor the courses that can be taken now. - Loop over every course and push those with
in_degree[course] == 0onto the back of the queue. - Start
takenat 0. - Loop while the queue isn't empty. Each course enters the queue at most once, so this runs at most
num_coursestimes. - Take the course at the front with
pop_front().unwrap()and add 1 totaken. Theunwrapis safe because the loop condition just checked that the queue has an element. - Loop over the courses that wait for it, using the pattern
&next_courseover&graph[course]. - Subtract 1 from
in_degree[next_course]: one of its prerequisites is done. - If the count reaches 0, push
next_courseonto the queue. - Return
taken == num_coursesas 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 becauseVecimplementsClone, and the annotation ongraphtells the compiler what kind of vector is inside.- Index types. The input numbers are
i32, but indexes must beusize, so each value taken fromprerequisitesis cast withas usize. The numbers pushed intographare alreadyusize, so the loop later needs no cast. - The type of
taken.taken == num_coursescompares with ani32, so Rust infers thattakenis ani32too. The vectorin_degreehas no stated element type, and with no other constraint Rust usesi32for it as well. for &next_course in &graph[course]. Iterating over a borrowed vector yields references, and the pattern&next_coursecopies the number out of each one. This also keepsgraphborrowed only for reading, so the loop body is free to changein_degreeandqueue.VecDeque. It is a double-ended queue instd::collections.push_backandpop_frontboth take constant time. A plainVecwould make removing from the front slow.- Final expression.
taken == num_courseshas no semicolon, so it is theboolthat 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 returnstrueas well. - Reading the pair backwards. In
[a, b], courseais the one that waits. Soagoes intograph[b], and it isin_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,
takenstays 0, and the answer isfalse. - 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_degreeonly once per pair. The pairs are distinct, so each arrow is used exactly once.
Testing
num_courses = 2,prerequisites = [[1, 0]]givestrue.num_courses = 2,prerequisites = [[1, 0], [0, 1]]givesfalse.num_courses = 4,prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]givestrue.num_courses = 1,prerequisites = []givestrue.num_courses = 3,prerequisites = [[1, 0], [2, 1], [1, 2]]givesfalse.
