Course Schedule, visualized step by step

Medium One of the Blind 75 interview problems (LeetCode 207). Technique: topological sort. Solution in Python, explained at every step.

The problem

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.

5 courses: arrows from 0 to 1 and to 2, from 1 and from 2 to 3, and from 3 to 4; answer: yes. 2 courses: an arrow from 0 to 1 and another from 1 back to 0, a cycle; answer: no.
Each pair [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.

Brute force

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.

The key insight

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.

Step by step

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.

Course Schedule, step by step

Python

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
All steps as text
  1. Each arrow leads from a course to a course that needs it. Can all five courses be taken?
  2. after lists the courses each course opens; indegree, beside each course, counts its missing prerequisites: 0 so far.
  3. The first pair, [1, 0], gives course 1 and before 0: course 1 needs course 0, the arrow 0 → 1, noted in after[0].
  4. The count of course 1 goes up by 1, to 1.
  5. The pair [2, 0]: course 2 needs course 0, the arrow 0 → 2.
  6. The count of course 2 goes up by 1, to 1.
  7. The pair [3, 1]: course 3 needs course 1, the arrow 1 → 3.
  8. The count of course 3 goes up by 1, to 1.
  9. The pair [3, 2]: course 3 needs course 2 too, the arrow 2 → 3.
  10. The count of course 3 goes up by 1, to 2.
  11. The pair [4, 3]: course 4 needs course 3, the arrow 3 → 4.
  12. The count of course 4 goes up by 1, to 1.
  13. Only course 0 has a count of 0: it goes into the queue, which holds the courses that can be taken now.
  14. The count taken starts at 0. It counts the courses taken so far: if it reaches 5, every course can be taken.
  15. Take course 0 out of the queue into curr, the course being taken now.
  16. taken goes up by 1, to 1.
  17. nxt goes through the courses that curr opens, after[0]. The first is course 1.
  18. Course 1 needed course 0, so its count drops by 1, to 0.
  19. The count of course 1 is 0: nothing it needs is missing, so it goes into the queue.
  20. The next course in after[0] is 2.
  21. Course 2 needed course 0, so its count drops by 1, to 0.
  22. Course 2's count is 0: it goes into the queue. after[0] is done: the next course comes out of the queue.
  23. Take course 1 out of the queue into curr.
  24. taken goes up by 1, to 2.
  25. nxt goes through after[1]. The first is course 3.
  26. Course 3 needed course 1, so its count drops by 1, to 1.
  27. Course 3's count is 1, not 0: it still waits for course 2. after[1] is done: the next course comes out of the queue.
  28. Take course 2 out of the queue into curr.
  29. taken goes up by 1, to 3.
  30. nxt goes through after[2]. The first is course 3.
  31. Course 3 needed course 2, so its count drops by 1, to 0.
  32. Course 3's count is 0: it goes into the queue. after[2] is done: the next course comes out of the queue.
  33. Take course 3 out of the queue into curr.
  34. taken goes up by 1, to 4.
  35. nxt goes through after[3]. The first is course 4.
  36. Course 4 needed course 3, so its count drops by 1, to 0.
  37. Course 4's count is 0: it goes into the queue. after[3] is done: the next course comes out of the queue.
  38. Take course 4 out of the queue into curr.
  39. taken goes up by 1, to 5. Course 4 opens no other course.
  40. The queue is empty, and taken is 5: every course was taken. The answer is yes.
  41. Every course entered the queue once and every prerequisite lowered one count once: O(V + E) time.
Course Schedule, step by step. Last step: Every course entered the queue once and every prerequisite lowered one count once: O(V + E) time.

Complexity

ApproachTimeSpace
Brute force: try every orderO(V! · E)O(V)
A search for a way back from every courseO(V · (V + E))O(V + E)
One depth-first search, with “in progress” and “done” marksO(V + E)O(V + E)
Count the prerequisites, take the courses with none left this pageO(V + E)O(V + E)

V is the number of courses, and E the number of prerequisite pairs.

  • Time: O(V + E). Building the lists reads every prerequisite once; then every course leaves the queue at most once, and every prerequisite lowers one count once.
  • Space: O(V + E). For the lists of courses each course opens, the counts and the queue.

Edge cases

  • A cycle, like [[0, 1], [1, 0]]: no course has a count of 0, so the queue starts empty, nothing is taken, and the function returns False.
  • No prerequisites at all: every count is 0, every course is in the queue from the start, and the answer is True.
  • A course that requires itself, [[0, 0]]: its count is 1 and only it could lower it, so it is never taken: False.
  • A cycle in one part only, like 0 → 1 fine and 2 ⇄ 3: courses 0 and 1 are taken, but 2 and 3 never are, so taken ends at 2 out of 4: False.

When the answer is no

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.

Course Schedule, when the answer is no

Python

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
All steps as text
  1. Each arrow leads from a course to a course that needs it. Can all four courses be taken?
  2. after lists the courses each course opens; indegree, beside each course, counts its missing prerequisites: 0 so far.
  3. The first pair, [1, 0], gives course 1 and before 0: course 1 needs course 0, the arrow 0 → 1, noted in after[0].
  4. The count of course 1 goes up by 1, to 1.
  5. The pair [2, 3]: course 2 needs course 3, the arrow 3 → 2.
  6. The count of course 2 goes up by 1, to 1.
  7. The pair [3, 2]: course 3 needs course 2, the arrow 2 → 3.
  8. The count of course 3 goes up by 1, to 1.
  9. Only course 0 has a count of 0: it goes into the queue, which holds the courses that can be taken now.
  10. The count taken starts at 0. It counts the courses taken so far: if it reaches 4, every course can be taken.
  11. Take course 0 out of the queue into curr, the course being taken now.
  12. taken goes up by 1, to 1.
  13. nxt goes through the courses that curr opens, after[0]. The first is course 1.
  14. Course 1 needed course 0, so its count drops by 1, to 0.
  15. Course 1's count is 0: it goes into the queue. after[0] is done: the next course comes out of the queue.
  16. Take course 1 out of the queue into curr.
  17. taken goes up by 1, to 2. Course 1 opens no other course.
  18. The queue is empty, and taken is 2, not 4: courses 2 and 3 wait on each other in a cycle. The answer is no.
  19. Courses 2 and 3 still have a count of 1: each waits for the other, so neither can go first.
Course Schedule, when the answer is no. Last step: Courses 2 and 3 still have a count of 1: each waits for the other, so neither can go first.

Try it: put Course Schedule together step by step

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.

Put Course Schedule together

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

Interview follow-up

Can 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).

The data structure behind it

  • Topological sort: Kahn's algorithm on a bigger graph, step by step.
  • Graph: vertices, edges and how a graph is stored as lists of neighbours.