There are n courses, numbered 0 to n − 1, and a list of prerequisites: a pair [a, b] means course b must be taken before course a. Can all the courses be finished?
Example: 5 courses with [[1, 0], [2, 0], [3, 1], [3, 2], [4, 3]]. Course 0 opens 1 and 2, both of them open 3, and 3 opens 4: yes, in the order 0, 1, 2, 3, 4. With [[0, 1], [1, 0]] instead, each of the two courses waits for the other, and the answer is no.
[a, b] is an arrow from b to a. With 2 courses the two arrows close a cycle, so neither course can ever be taken.Note
Watch the order inside a pair. Read [a, b] as a before b, and every arrow turns around. A graph and its reverse have the same cycles, so the answer to this question stays right, but an order built that way comes out backwards.
Try it yourself first: LeetCode 207 ↗. Then step through the solution below.
Try orders: check whether some ordering of the V courses puts every prerequisite first. There are V! orderings, so this is hopeless beyond a handful of courses. A smarter first idea, searching from every course for a path back to itself, is O(V × (V + E)) for V courses and E prerequisites.
A course with no prerequisites left can be taken now. Taking it may leave some other course with none left, which can then be taken too. So keep a count of missing prerequisites for each course, take the courses whose count is 0, and lower the counts of the courses they open.
If that takes every course, the answer is yes. If some courses are never taken, a cycle holds them back: the courses on it wait on each other, and the courses after it wait on them. The answer is no.
Note
This is Kahn's algorithm for topological sort: the courses leave the queue in an order that respects every prerequisite. The other classic answer is one depth-first search with two marks: “in progress” while the search is still inside a course, and “done” once it leaves it. Reaching an “in progress” course again is a cycle; a “done” course is skipped, so each course is searched once: O(V + E) too. Its classic slip is one set for both kinds of mark. On this page's example, the search from 1 has finished 3 and 4 when the search from 2 reaches 3 again: one set calls that a cycle, though there is none.
The player runs the code on the example. Press → for each step: the lines it runs light up in the code.
On a phone, Full screen keeps the picture and the code on one screen.
from collections import deque def can_finish(n, prereqs): after = [[] for _ in range(n)] indegree = [0] * n for course, before in prereqs: after[before].append(course) indegree[course] += 1 queue = deque(course for course in range(n) if indegree[course] == 0) taken = 0 while queue: curr = queue.popleft() taken += 1 for nxt in after[curr]: indegree[nxt] -= 1 if indegree[nxt] == 0: queue.append(nxt) return taken == n
Now write it yourself on LeetCode 207 ↗, or go on: all 8 interview problems →
after lists the courses each course opens; indegree, beside each course, counts its missing prerequisites: 0 so far.[1, 0], gives course 1 and before 0: course 1 needs course 0, the arrow 0 → 1, noted in after[0].[2, 0]: course 2 needs course 0, the arrow 0 → 2.[3, 1]: course 3 needs course 1, the arrow 1 → 3.[3, 2]: course 3 needs course 2 too, the arrow 2 → 3.[4, 3]: course 4 needs course 3, the arrow 3 → 4.taken starts at 0. It counts the courses taken so far: if it reaches 5, every course can be taken.curr, the course being taken now.taken goes up by 1, to 1.nxt goes through the courses that curr opens, after[0]. The first is course 1.after[0] is 2.after[0] is done: the next course comes out of the queue.curr.taken goes up by 1, to 2.nxt goes through after[1]. The first is course 3.after[1] is done: the next course comes out of the queue.curr.taken goes up by 1, to 3.nxt goes through after[2]. The first is course 3.after[2] is done: the next course comes out of the queue.curr.taken goes up by 1, to 4.nxt goes through after[3]. The first is course 4.after[3] is done: the next course comes out of the queue.curr.taken goes up by 1, to 5. Course 4 opens no other course.taken is 5: every course was taken. The answer is yes.| Approach | Time | Space |
|---|---|---|
| Brute force: try every order | O(V! · E) | O(V) |
| A search for a way back from every course | O(V · (V + E)) | O(V + E) |
| One depth-first search, with “in progress” and “done” marks | O(V + E) | O(V + E) |
| Count the prerequisites, take the courses with none left this page | O(V + E) | O(V + E) |
V is the number of courses, and E the number of prerequisite pairs.
[[0, 1], [1, 0]]: no course has a count of 0, so the queue starts empty, nothing is taken, and the function returns False.True.[[0, 0]]: its count is 1 and only it could lower it, so it is never taken: False.taken ends at 2 out of 4: False.The same code on the edge case above: course 0 opens course 1, and courses 2 and 3 each need the other. Press → for each step.
from collections import deque def can_finish(n, prereqs): after = [[] for _ in range(n)] indegree = [0] * n for course, before in prereqs: after[before].append(course) indegree[course] += 1 queue = deque(course for course in range(n) if indegree[course] == 0) taken = 0 while queue: curr = queue.popleft() taken += 1 for nxt in after[curr]: indegree[nxt] -= 1 if indegree[nxt] == 0: queue.append(nxt) return taken == n
after lists the courses each course opens; indegree, beside each course, counts its missing prerequisites: 0 so far.[1, 0], gives course 1 and before 0: course 1 needs course 0, the arrow 0 → 1, noted in after[0].[2, 3]: course 2 needs course 3, the arrow 3 → 2.[3, 2]: course 3 needs course 2, the arrow 2 → 3.taken starts at 0. It counts the courses taken so far: if it reaches 4, every course can be taken.curr, the course being taken now.taken goes up by 1, to 1.nxt goes through the courses that curr opens, after[0]. The first is course 1.after[0] is done: the next course comes out of the queue.curr.taken goes up by 1, to 2. Course 1 opens no other course.taken is 2, not 4: courses 2 and 3 wait on each other in a cycle. The answer is no.The blocks below are steps of Course Schedule in words, and one of them does not belong. Put the right ones in order and check: your algorithm runs on the example and on its edge case, where courses 2 and 3 need each other, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.
Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. One of them doesn't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.
Your algorithm
Blocks
Now write it yourself on LeetCode 207 ↗, or go on: all 8 interview problems →
from collections import deque def can_finish(n, prereqs): after = [[] for _ in range(n)] indegree = [0] * n for course, before in prereqs: after[before].append(course) indegree[course] += 1 queue = deque(course for course in range(n) if indegree[course] == 0) taken = 0 while queue: curr = queue.popleft() taken += 1 for nxt in after[curr]: indegree[nxt] -= 1 if indegree[nxt] == 0: queue.append(nxt) return taken == nCan you return an order to take the courses? Yes: add each course to a list as it leaves the queue. If the list ends with all V courses, it is a valid order; if it is shorter, there is a cycle and no order exists. Same O(V + E). This is Course Schedule II (LeetCode 210).
LeetCode is a trademark of LeetCode LLC. VisiGrab is not affiliated with LeetCode or with Blind; the problems are told in our own words, with our own examples.