Problem overview
The function canFinish receives numCourses and an Array<IntArray> named prerequisites. A pair [a, b] means course b must be taken before course a. The function returns true if every course can be taken in some order that respects all the pairs, and false otherwise.
With numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], course 0 needs nothing, courses 1 and 2 need course 0, and course 3 needs both 1 and 2. The order 0, 1, 2, 3 works, so the answer is true. With [[1, 0], [0, 1]] each of the two courses waits for the other, so neither can ever be taken and the answer is false.
Approach: take free courses first
Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that needs it. An order of all the courses in which every arrow points forward is a topological order. All courses can be finished exactly when such an order exists, which happens exactly when the arrows contain no cycle.
Kahn's algorithm builds the order greedily:
- Count, for each course, how many prerequisites it still waits for. This count is its in-degree, the number of arrows pointing into it.
- Put every course whose count is 0 into a queue. These can be taken right now.
- Take a course from the queue. Each course that waits for it now has one prerequisite fewer. If a count drops to 0, that course joins the queue.
- Repeat until the queue is empty, and count how many courses were taken.
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 needs one of them. So the answer is whether the number of courses taken equals numCourses.
The work is O(V + E) for V courses and E pairs, which matters because both can reach 100,000. A recursive depth-first search for cycles is another option, but the queue-based version has no recursion to overflow.
Step by step
- Build
graph.Array(numCourses) { mutableListOf<Int>() }creates one empty mutable list per course.graph[b]will hold the courses that wait for courseb. - Create
inDegree, anIntArrayof zeros.inDegree[a]counts the prerequisites of courseathat haven't been taken. - Loop over
prerequisites. For each pair, addprereq[0]tograph[prereq[1]]and increaseinDegree[prereq[0]]by one. - Create the
queue, anArrayDeque<Int>. Adding at the back and removing from the front are bothO(1). - Seed the queue. Loop over
0 until numCoursesand add each course withinDegree[course] == 0. If there are none, every course waits for another, and nothing can start. - Declare
takenas avarat 0. It counts the courses taken. - Run the queue. While it isn't empty, remove the front course, increase
taken, and loop overgraph[course]. - Update each waiting course. Decrease
inDegree[nextCourse]. If it reaches 0, addnextCourseto the queue. A count reaches 0 only once, so each course enters the queue at most once. - Return
taken == numCourses.
The solution in Kotlin
class Solution {
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
val graph = Array(numCourses) { mutableListOf<Int>() }
val inDegree = IntArray(numCourses)
for (prereq in prerequisites) {
graph[prereq[1]].add(prereq[0])
inDegree[prereq[0]]++
}
val queue = ArrayDeque<Int>()
for (course in 0 until numCourses) {
if (inDegree[course] == 0) {
queue.add(course)
}
}
var taken = 0
while (queue.isNotEmpty()) {
val course = queue.removeFirst()
taken++
for (nextCourse in graph[course]) {
inDegree[nextCourse]--
if (inDegree[nextCourse] == 0) {
queue.add(nextCourse)
}
}
}
return taken == numCourses
}
}
On the third example, the tables right after the loop over prerequisites, and then the state after each course is taken, look like this:
graph=[[1, 2], [3], [3], []] inDegree=[0, 1, 1, 2]
take 0 inDegree=[0, 0, 0, 2]
take 1 inDegree=[0, 0, 0, 1]
take 2 inDegree=[0, 0, 0, 0]
take 3 inDegree=[0, 0, 0, 0]
Course 3 enters the queue only when its count reaches 0, after both 1 and 2 have been taken. All four courses are taken, so the function returns true.
The Kotlin details worth knowing:
- One list per course. The block in
Array(numCourses) { ... }runs once per index, so each slot gets its ownMutableList. Filling the array with one shared list would mix all the courses together. kotlin.collections.ArrayDeque.ArrayDequeis available in Kotlin without any import. It offersadd,removeFirstandisNotEmpty. CallingremoveFirston an empty deque throws, which is why the loop checksisNotEmpty()first.inDegree[prereq[0]]++changes an element of anIntArrayin place. The array reference is aval, but its elements are mutable.- Modifying while iterating. The inner
forreadsgraph[course]and only changesinDegreeandqueue, never the list being walked, so it is safe.
Complexity
Time: O(V + E). Building the graph touches each pair once. Seeding the queue looks at each course once. Each course is removed from the queue at most once, and its list is walked once, so over the whole run every pair is examined once.
Space: O(V + E). The adjacency lists hold one entry per pair, and inDegree, the queue and the array of lists hold at most one entry per course.
Edge cases and common mistakes
- No prerequisites. Every count is 0, every course goes into the queue, and the result is
true. This is true fornumCourses = 3and an empty array. - Reversed arrows. In
[a, b],bcomes first. The solution storesaingraph[b]and counts the in-degree ofa. Mixing the two up reverses every arrow, and the counts then no longer match the steps of the lesson. - A cycle hiding behind free courses. With
numCourses = 3and[[1, 0], [2, 1], [1, 2]], course 0 is free, but courses 1 and 2 wait for each other. Only course 0 is taken, and the result isfalse. - Returning
truewhen the queue starts non-empty. Some free courses don't prove the schedule works. Only the final count of taken courses does.
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 = 3,prerequisites = [[1, 0], [2, 1], [1, 2]]givesfalse.numCourses = 1,prerequisites = []givestrue.
