Problem overview
The function canFinish receives numCourses, the number of courses (labelled 0 to numCourses - 1), and prerequisites, a slice of pairs. A pair [a, b] means course b must be taken before course a. The function returns true when some order lets you take every course, and false otherwise.
With numCourses = 2 and prerequisites = [[1, 0]] the answer is true: take course 0, then course 1. With prerequisites = [[1, 0], [0, 1]] the answer is false, because each course waits for the other and neither can start. With numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] the answer is true: 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 free courses and unlock the rest
Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that depends on it. All courses can be finished exactly when there is an order 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 that order directly:
- Count, for every course, how many prerequisites it still waits for. This count is its in-degree, the number of arrows pointing into it.
- Put every course with a count of 0 in a queue. These can be taken right now.
- Take a course from the queue. For each course that waits for it, lower that course's count by 1. If a count reaches 0, that course is free: add it to the queue.
- Repeat until the queue is empty, and count the courses taken.
If every course was taken, the answer is true. Courses on a cycle wait for each other, so their counts never reach 0 and they are never taken. The same holds for any course that depends on one of them. If any course is left over, the answer is false.
Each course enters the queue at most once and each arrow is looked at once, so the work grows with the number of courses plus the number of pairs.
Step by step
- Create
graphas a slice ofnumCoursesint slices withmake.graph[b]will hold the courses that wait for courseb. The inner slices start asnil, andappendworks on anilslice, so they need no setup. - Create
inDegree, a slice ofnumCoursesints.makefills it with zeros. - Loop over
prerequisiteswithrange, naming each pairprereq. - Record the arrow. Append
prereq[0]tograph[prereq[1]], and store the result back, becauseappendreturns the grown slice. - Count the prerequisite. Add 1 to
inDegree[prereq[0]]. - Create the queue as an empty int slice,
[]int{}. A slice works as a queue:appendadds at the back and reslicing removes the front. - Seed the queue. Loop over every course and append the ones whose
inDegreeis 0. - Start a counter named
takenat 0. - Loop while
len(queue) > 0. Go'sforwith only a condition plays the role ofwhile. - Take the front course. Copy
queue[0]intocourse, drop it withqueue = queue[1:], and add 1 totaken. - Unlock the dependants. Range over
graph[course]. For eachnextCourse, subtract 1 from its in-degree, and if that reaches 0, append it to the queue. - Return
taken == numCourses.
The solution in Go
func canFinish(numCourses int, prerequisites [][]int) bool {
graph := make([][]int, numCourses)
inDegree := make([]int, numCourses)
for _, prereq := range prerequisites {
graph[prereq[1]] = append(graph[prereq[1]], prereq[0])
inDegree[prereq[0]]++
}
queue := []int{}
for course := 0; course < numCourses; course++ {
if inDegree[course] == 0 {
queue = append(queue, course)
}
}
taken := 0
for len(queue) > 0 {
course := queue[0]
queue = queue[1:]
taken++
for _, nextCourse := range graph[course] {
inDegree[nextCourse]--
if inDegree[nextCourse] == 0 {
queue = append(queue, nextCourse)
}
}
}
return taken == numCourses
}
The Go details worth a closer look:
appendmust be assigned.appendmay allocate a bigger array, so it returns the new slice. Writingappend(graph[prereq[1]], prereq[0])on its own line would discard the result, and Go rejects it with an error that the value is not used.make([][]int, n)givesnnil slices. Readinggraph[x]for a course nobody depends on gives an empty slice, and ranging over it does nothing.- Reslicing as a dequeue.
queue[1:]does not copy anything; it moves the start of the slice forward. Each course is appended once, so the total work stays linear. rangewith_.rangeyields an index and a value. A variable you don't use is a compile error in Go, so the index is dropped with_.++and--are statements.inDegree[prereq[0]]++works on its own line, but it can't be used inside an expression.
A trace
For numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], the graph and in-degrees are built first. Then each line below is printed after a course is taken:
graph [[1 2] [3] [3] []] inDegree [0 1 1 2]
took 0 inDegree [0 0 0 2] queue [1 2] taken 1
took 1 inDegree [0 0 0 1] queue [2] taken 2
took 2 inDegree [0 0 0 0] queue [3] taken 3
took 3 inDegree [0 0 0 0] queue [] taken 4
Now a case with a cycle: numCourses = 4 and prerequisites = [[1, 0], [2, 1], [1, 2], [3, 0]]. Courses 1 and 2 need each other.
graph [[1 3] [2] [1] []] inDegree [0 2 1 1]
took 0 inDegree [0 1 1 0] queue [3] taken 1
took 3 inDegree [0 1 1 0] queue [] taken 2
Only 2 of 4 courses are taken. Courses 1 and 2 keep a count of 1 forever, so the function returns false.
Complexity
Let V be numCourses and E the number of pairs.
Time: O(V + E). Building the graph touches each pair once. Seeding the queue checks each course once. Each course is taken at most once, and when it is taken, its list of dependants is walked once, which covers every pair exactly one time over the whole run.
Space: O(V + E). graph holds one entry per pair, and inDegree and the queue hold at most one entry per course.
Edge cases and common mistakes
- No prerequisites. Every in-degree is 0, every course goes in the queue, and the result is
true. This works fornilas well as an empty slice. - A single course.
numCourses = 1with no pairs returnstrue. - Cycles of any length. The two-course cycle is the smallest, but a cycle through three courses,
[[0, 1], [1, 2], [2, 0]], returnsfalsetoo: no course starts with a count of 0, so the queue starts empty. - A cycle in one part of the graph. Other courses can still be taken, but the final comparison with
numCoursesfails. Checking only that the queue starts non-empty is not enough. - Reversing the arrow. In
[a, b]the course to take first isb. Addingbtograph[a]and countingb's in-degree would answer for the reverse graph. That happens to give the same true or false answer, but the order in which courses are taken would be wrong, so keep the arrow direction as the statement gives it. - Forgetting to store
append's result. The queue or the graph stays unchanged, and the code either fails to compile or gives wrong answers. - Queueing a course twice. A course is queued only when its count reaches exactly 0, and a count reaches 0 only once, so no check for duplicates is needed.
Testing
numCourses = 2,prerequisites = [[1, 0]]givestrue.numCourses = 2,prerequisites = [[1, 0], [0, 1]]givesfalse.numCourses = 4,prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]givestrue.numCourses = 1,prerequisites = []givestrue.numCourses = 3,prerequisites = [[0, 1], [1, 2], [2, 0]]givesfalse.numCourses = 4,prerequisites = [[1, 0], [2, 1], [1, 2], [3, 0]]givesfalse.
