Problem overview
The method canFinish(numCourses: Int, prerequisites: Array[Array[Int]]): Boolean receives the number of courses and a list of pairs. A pair [a, b] means course b must be taken before course a. The method returns true if all the courses can be taken in some order and false otherwise.
With numCourses = 2 and [[1, 0]], take course 0, then course 1: true. With [[1, 0], [0, 1]], each course waits for the other, so neither can start: false.
Approach: take whatever is free
Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that needs it. All the courses can be finished exactly when the arrows contain no cycle, that is, when the courses can be put in a line so that every arrow points forward. Such a line is a topological order.
Kahn's algorithm builds that line greedily. A course with no prerequisites left can be taken right away. Taking it removes its arrows, and any course that was waiting only for it becomes free. Repeat until nothing is free. If every course got taken, the answer is true. If some are left, each of them waits, directly or not, for a course on a cycle, so the answer is false.
To make "no prerequisites left" cheap to check, keep for each course a count of its untaken prerequisites, its in-degree, and for each course a list of the courses that wait for it.
Why does a cycle always block the process? Take any course on a cycle: one of its prerequisites is the previous course on that cycle, which is itself waiting for the course before it, and so on around the loop. None of them ever reaches an in-degree of 0, so none enters the queue. The same goes for any course that depends on one of them, which is why a single cycle anywhere can make the answer false. The other direction holds too: if there is no cycle, there is always at least one course with no untaken prerequisites, so the process never gets stuck before the end.
Step by step
- Create
graph: an array ofnumCoursesemptymutable.ArrayBuffer[Int]s.graph(b)will list the courses that wait for courseb. - Create
inDegree, an array ofnumCourseszeros.inDegree(a)will count the prerequisites of coursea. - Loop over the pairs. For each, append
prereq(0)tograph(prereq(1))and add 1 toinDegree(prereq(0)). - Create a
mutable.Queue[Int]and enqueue every course whoseinDegreeis 0: those can be taken first. - Keep a
var takencounter, starting at 0. - While the queue isn't empty, dequeue a course and add 1 to
taken. Then go through the courses that wait for it, subtracting 1 from each one'sinDegree. When one reaches 0, enqueue it. A count reaches 0 only once, so no course is queued twice. - The last line,
taken == numCourses, is the result.
The solution in Scala
class Solution {
def canFinish(numCourses: Int, prerequisites: Array[Array[Int]]): Boolean = {
val graph = Array.fill(numCourses)(mutable.ArrayBuffer[Int]())
val inDegree = Array.fill(numCourses)(0)
for (prereq <- prerequisites) {
graph(prereq(1)) += prereq(0)
inDegree(prereq(0)) += 1
}
val queue = mutable.Queue[Int]()
for (course <- 0 until numCourses) {
if (inDegree(course) == 0) {
queue.enqueue(course)
}
}
var taken = 0
while (queue.nonEmpty) {
val course = queue.dequeue()
taken += 1
for (nextCourse <- graph(course)) {
inDegree(nextCourse) -= 1
if (inDegree(nextCourse) == 0) {
queue.enqueue(nextCourse)
}
}
}
taken == numCourses
}
}
The solution uses mutable.ArrayBuffer and mutable.Queue. In a file of your own, add import scala.collection.mutable at the top.
Scala details
Array.fill(numCourses)(mutable.ArrayBuffer[Int]())evaluates its second argument once per element, so each course gets its own buffer. Putting one buffer in a variable first and filling the array with that variable would make every entry the same buffer: appending 5 to the first entry would show up in the second too.- Scala has no
++: counters change with+= 1and-= 1.graph(b) += aon a buffer appends an element. 0 until numCoursesexcludes the end;1 to nwould include it.- A
forloop overgraph(course)only reads the buffer while the loop runs; nothing here changes it, so iterating is safe. queue.dequeue()throws on an empty queue, which is why the loop checksnonEmptyfirst.
Tracing the third example
For numCourses = 4 and pairs [1, 0], [2, 0], [3, 1], [3, 2], the setup gives:
graph: [1, 2] [3] [3] []
inDegree: [0, 1, 1, 2]
Only course 0 starts in the queue. Taking each course in turn:
took 0: inDegree=[0, 0, 0, 2] queue=[1, 2]
took 1: inDegree=[0, 0, 0, 1] queue=[2]
took 2: inDegree=[0, 0, 0, 0] queue=[3]
took 3: inDegree=[0, 0, 0, 0] queue=[]
Four courses were taken, so the method returns true.
Complexity
Time is O(V + E) for V courses and E pairs: building the graph visits each pair once, and the queue loop takes each course once and looks at each arrow once. Space is O(V + E) for the buffers, the counts and the queue.
Edge cases and common mistakes
- No prerequisites: every course starts in the queue and the answer is
true. Both 5 courses and 1 course with an empty list returntrue. - A cycle next to free courses: with 3 courses and pairs
[1, 0],[2, 1],[1, 2], course 0 can be taken, but courses 1 and 2 wait for each other. The method returnsfalse, because only 1 of 3 was taken. - Swapped direction: the pair
[a, b]puts the arrow frombtoa. Reversing it everywhere still gives a correct yes or no, but mixing the two directions does not. - Returning when the queue starts empty: if no course is free at the start,
takenstays 0 and the result isfalsewith no special case. - Large inputs: the method is iterative, so a chain of 100000 courses, each needing the previous one, returns
truewithout stack problems. A recursive depth-first search would need care there.
