Problem overview
The method canFinish receives numCourses and a list prerequisites. Each pair [a, b] means course b must be taken before course a. It returns True if all the courses can be finished and False otherwise.
With numCourses = 2 and prerequisites = [[1, 0]], you take course 0 and then course 1, so the answer is True. With [[1, 0], [0, 1]] each course waits for the other, so neither can ever be taken and the answer is False.
Approach: take what is free, and unlock what it leads to
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 you can line them up so that every arrow points forward. Such an order is called a topological order, and it exists exactly when the arrows form no cycle.
Kahn's algorithm builds that order one course at a time:
- Count, for every course, how many prerequisites it still waits for. This is its in-degree, the number of arrows pointing into it.
- Put every course with a count of 0 into a queue. They can be taken now.
- Take a course from the queue. For each course that waits for it, lower that course's count by one. If a count reaches 0, the course is free: add it to the queue.
- Repeat until the queue is empty.
Courses on a cycle wait for each other, so their counts never reach 0 and they never enter the queue. Neither does any course that needs one of them. So if the number of courses taken equals numCourses, there is no cycle. If it is smaller, there is one.
Every pair is looked at once, when its first course is taken, so the work is proportional to the number of courses plus the number of pairs.
Step by step
- Build the graph.
graphis a list ofnumCoursesempty lists made with a list comprehension.graph[b]will hold the courses that wait for courseb. - Create
inDegree, a list ofnumCourseszeros.inDegree[a]counts the prerequisites of courseathat haven't been taken yet. - Loop over
prerequisiteswith the variableprereq. Each pair becomes one arrow. - Record the arrow. Append
prereq[0]tograph[prereq[1]]: courseprereq[1]comes first, andprereq[0]waits for it. - Count the prerequisite. Add 1 to
inDegree[prereq[0]]. - Create an empty deque named
queue, for the courses that can be taken now. A deque adds at the back withappendand removes from the front withpopleft, both in constant time. - Look at every course, with
courseoverrange(numCourses), and append the ones whoseinDegreeis 0. Any valid order starts with courses that need nothing. If there are none, every course waits for another one. - Start
takenat 0. It counts the courses we manage to take. - Loop while
queueis not empty. An empty deque counts as false, sowhile queue:is enough. - Take the front course with
popleftand add 1 totaken. Everything in the queue has all its prerequisites taken, so taking it is safe, and courses come out in a topological order. - Visit the courses that wait for it,
nextCourseovergraph[course], and subtract 1 frominDegree[nextCourse]. - Free the ones that reach 0. When a count hits 0, the last prerequisite was just taken, so append
nextCourseto the queue. A count reaches 0 only once, so each course enters the queue at most once. - Return
taken == numCourses.
The solution in Python
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = [[] for _ in range(numCourses)]
inDegree = [0] * numCourses
for prereq in prerequisites:
graph[prereq[1]].append(prereq[0])
inDegree[prereq[0]] += 1
queue = deque()
for course in range(numCourses):
if inDegree[course] == 0:
queue.append(course)
taken = 0
while queue:
course = queue.popleft()
taken += 1
for nextCourse in graph[course]:
inDegree[nextCourse] -= 1
if inDegree[nextCourse] == 0:
queue.append(nextCourse)
return taken == numCourses
Python details worth knowing
- Build the lists with a comprehension.
[[] for _ in range(numCourses)]creates a separate empty list for each course. Writing[[]] * numCoursesrepeats one list object, so every slot is the same list. Afterg = [[]] * 3andg[0].append(1),gis[[1], [1], [1]]. With the comprehension, the same append gives[[1], [], []]. [0] * numCoursesis safe for numbers. Integers are immutable, soinDegree[a] += 1replaces one slot's value and doesn't touch the others.- Use a deque, not
list.pop(0). Removing the first item of a list shifts all the others, which costs time proportional to the list's length.deque.popleft()doesn't. It comes from thecollectionsmodule.
Trace on the third example
For numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], the arrays after the first loop are graph = [[1, 2], [3], [3], []] and inDegree = [0, 1, 1, 2]. Only course 0 starts in the queue. Each turn of the main loop then looks like this:
| Course taken | inDegree afterwards | queue afterwards |
|---|---|---|
| 0 | [0, 0, 0, 2] | [1, 2] |
| 1 | [0, 0, 0, 1] | [2] |
| 2 | [0, 0, 0, 0] | [3] |
| 3 | [0, 0, 0, 0] | [] |
Four courses were taken, which equals numCourses, so the result is True. Course 3 only entered the queue after both 1 and 2 were taken, because its count needed two decrements to reach 0.
Complexity
Time: with V courses and E pairs, building the graph is O(V + E). Each course enters the queue at most once and is taken once. Each pair is looked at once, when its first course is taken. In total that is O(V + E).
Space: graph holds V lists and E entries, inDegree holds V counts, and the queue holds at most V courses, so the space is O(V + E).
Edge cases and common mistakes
- No prerequisites. Every count is 0, every course goes into the queue, and the result is
True. FornumCourses = 3andprerequisites = []the method takes 0, 1 and 2 and returnsTrue. - A cycle that doesn't include every course. With
numCourses = 3and[[1, 0], [2, 1], [1, 2]], course 0 is free and gets taken, but courses 1 and 2 wait for each other.takenends at 1, not 3, so the result isFalse. This is why the final check compares againstnumCoursesinstead of asking whether the queue ever ran. - Arrow direction. The pair
[a, b]meansbcomes first. Storing the arrow asgraph[a]holdingbreverses the whole graph, and the counts then describe the wrong courses. - Queueing a course twice. Add a course only at the moment its count reaches exactly 0, not whenever the count is "small".
- Sharing one list. Building
graphwith[[]] * numCoursesmixes all the courses' lists together.
Testing
These results come from running the solution:
| numCourses | prerequisites | Result |
|---|---|---|
| 2 | [[1, 0]] | True |
| 2 | [[1, 0], [0, 1]] | False |
| 4 | [[1, 0], [2, 0], [3, 1], [3, 2]] | True |
| 3 | [[1, 0], [2, 1], [1, 2]] | False |
| 3 | [] | True |
