Problem overview
The method canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool receives the number of courses, labeled 0 to numCourses - 1, and a list of pairs. A pair [a, b] means course b must be taken before course a. It returns true if all the courses can be finished.
With numCourses = 2 and prerequisites = [[1, 0]] the answer is true: take course 0, then course 1. With [[1, 0], [0, 1]] the answer is false, because each course waits for the other and neither can start.
Drawing each pair [a, b] as an arrow from b to a, the courses can all be finished exactly when the arrows contain no cycle. In that case an order exists in which every arrow points forward, called a topological order.
Approach: keep taking courses that are free
A course is free when none of its prerequisites is left untaken. Start with the courses that need nothing. Taking one removes its arrows, which may free other courses. Repeat until no free course remains, and count how many were taken. If the count equals numCourses, every course was reachable in some valid order. Otherwise the leftover courses are on a cycle, or wait for one, and the answer is false.
This is Kahn's algorithm. To do it fast, two things are stored:
graph[b]lists the courses that wait for courseb.inDegree[a]counts how many prerequisites of courseaare still untaken.
A course is free when its count is 0. Every pair is looked at once while building the data and once while taking courses, so the work is O(V + E) for V courses and E pairs. A depth-first search that looks for cycles is another way to solve the problem, but this lesson uses the counting approach.
Step by step
- Create
graphwith[[Int]](repeating: [], count: numCourses): one empty list per course. - Create
inDegreeasnumCourseszeros. - Loop over the pairs. For each
prereq,prereq[1]comes first andprereq[0]waits for it. - Record the arrow: append
prereq[0]tograph[prereq[1]]. - Count the prerequisite:
inDegree[prereq[0]] += 1. - Create
queueas an empty[Int]()that will hold the free courses. - Seed the queue. Loop over every course and append those with
inDegree[course] == 0. These are the valid starting points. - Create
taken, starting at 0. It counts the courses taken and is also the position inqueueof the next one to take. - Loop while
taken < queue.count. The queue grows during the loop as courses become free. - Read the next course with
queue[taken]and add 1 totaken. - Visit the courses waiting for it: loop over
graph[course]. - Remove one prerequisite from each with
inDegree[nextCourse] -= 1. - If its count reaches 0, append it to the queue. A count reaches 0 only once, so each course joins the queue at most once.
- Return
taken == numCourses.
The solution in Swift
class Solution {
func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
var graph = [[Int]](repeating: [], count: numCourses)
var inDegree = [Int](repeating: 0, count: numCourses)
for prereq in prerequisites {
graph[prereq[1]].append(prereq[0])
inDegree[prereq[0]] += 1
}
var queue = [Int]()
for course in 0..<numCourses {
if inDegree[course] == 0 {
queue.append(course)
}
}
var taken = 0
while taken < queue.count {
let course = queue[taken]
taken += 1
for nextCourse in graph[course] {
inDegree[nextCourse] -= 1
if inDegree[nextCourse] == 0 {
queue.append(nextCourse)
}
}
}
return taken == numCourses
}
}
The Swift details worth a closer look:
- Arrays are values.
[[Int]](repeating: [], count: numCourses)fills the outer array with copies of the empty array. Each course gets its own inner array, and appending tograph[2]doesn't touchgraph[3]. - The queue is an array read by index.
removeFirst()shifts every remaining element, which is slow for a long queue. The code never removes anything:takenmarks the front, and the entries before it are courses already taken. - The loop condition is re-checked each turn.
queue.countchanges inside the loop, and thewhilesees the new value. - No
++. Swift has no increment operator, so the code uses+= 1and-= 1. letforcourse. It never changes after it is read, soletsays so.
Tracing two inputs
For numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], the setup gives:
graph=[[1, 2], [3], [3], []] inDegree=[0, 1, 1, 2]
queue=[0, 1, 2, 3] taken=4
Only course 0 starts free. Taking it frees courses 1 and 2. Taking those frees course 3. All four are taken, so the result is true.
Now add a cycle: numCourses = 4 and prerequisites = [[1, 0], [2, 1], [1, 2], [3, 0]]. Courses 1 and 2 wait for each other:
graph=[[1, 3], [2], [1], []] inDegree=[0, 2, 1, 1]
queue=[0, 3] taken=2
Course 0 is taken and frees course 3, but course 1 still waits for course 2 and vice versa. Only 2 courses are taken, so the result is false.
Complexity
Time: O(V + E). Building graph and inDegree touches each pair once. Seeding the queue looks at each course once. Each course enters the queue at most once, and its list is scanned once, so the main loop looks at each pair once.
Space: O(V + E). graph holds one entry per pair, and inDegree and queue hold at most one entry per course.
Edge cases and common mistakes
- No prerequisites. Every course starts free, so
canFinish(3, [])returnstrue. - Reversed arrows. In
[a, b],bcomes first. Storing the arrow the other way round counts the wrong thing, although some inputs still give the right answer by accident. - A cycle away from the start. Course 0 may be free while a different group of courses loops. The answer is
false, which is why the result comparestakenwithnumCoursesinstead of checking that the queue started non-empty. - Courses that depend on a cycle. A course that needs a cyclic course never reaches count 0 either, so it is never taken.
- Using
removeFirst()on a big queue. It still gives correct answers, but each call moves the remaining elements, which can make a long run slow. - Long chains. There is no recursion, so a chain of 100,000 courses, each needing the one before it, returns
truewithout stack problems.
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 = []givestrue.numCourses = 4,prerequisites = [[1, 0], [2, 1], [1, 2], [3, 0]]givesfalse.
