Course Schedule
Check whether every course can be finished given its prerequisites
DSA, Medium, Graphs
Which structure or algorithm, and what does it cost.
You must take n courses, numbered 0 to n - 1. Each pair [a, b] in rules means course b must be finished before course a starts. You take one course at a time. Return true if some order finishes every course. Return false if the rules make that impossible. A pair may repeat, and a pair may name the same course twice.
Examples
Constraints
- 1 <=
n<= 100,000. - 0 <= number of pairs <= 200,000.
- Every course number is between 0 and n - 1.
Your answer must contain
- Why a circle of rules makes the answer false; the method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n + r) time and memory, where r is the number of pairs.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Draw each course as a dot and each rule as an arrow from the course to finish first to the course that needs it. What shape makes finishing impossible?
Hint 2 the approach
Impossible means a circle of rules. Which course can you always take right now? Taking it may free other courses.
Hint 3 the key step
Count the rules each course still waits on. Take any course at zero, lower the counts of courses that need it, repeat. Compare courses taken with n.
Walkthrough
Full walkthrough brute force to best
Brute force
Try every order of the courses and check every rule against it. There are n! orders, so this only works for tiny n.
Better method
Depth-first search with three states for each course: not seen, in progress, done. Walk along the arrows from every course. If you reach a course that is in progress, you found a circle, so return false. This is O(n + r) time, but the recursion can go n deep, which needs care for 100,000 courses.
Best method
Count, for each course, how many rules it still waits on. Put every course with a count of 0 in a queue. Take a course from the queue, count it as done, and lower the count of every course that needed it. A course that reaches 0 joins the queue. A course inside a circle never reaches 0, because it waits on a course that waits on it. So when the queue is empty, the answer is true exactly when the number of courses taken equals n. This method is called a topological sort. The same shape fits any question about doing tasks in an order that respects dependencies.
Hand trace
Example 1: the counts are [0, 1, 1, 2, 1] and the queue is [0]. Take 0: courses 1 and 2 drop to 0, so the queue is [1, 2]. Take 1: course 3 drops to 1. Take 2: course 3 drops to 0, so the queue is [3]. Take 3: course 4 drops to 0, so the queue is [4]. Take 4. Five courses were taken and n is 5, so the answer is true.
Code
from collections import deque
def can_finish(n, rules):
after = [[] for _ in range(n)] # after[b] = courses that need b first
waiting = [0] * n # rules each course still waits on
for a, b in rules:
after[b].append(a)
waiting[a] += 1
ready = deque(i for i in range(n) if waiting[i] == 0)
done = 0
while ready:
c = ready.popleft()
done += 1
for nxt in after[c]:
waiting[nxt] -= 1
if waiting[nxt] == 0:
ready.append(nxt)
return done == nTime and memory
O(n + r) time and O(n + r) memory, where r is the number of pairs. Each course and each pair is handled once.
Common mistakes
- Reading each pair backwards. In [a, b] the course b comes first, so the arrow goes from b to a.
- Checking only that the queue starts non-empty. A circle can hide behind courses that do start, so compare the number taken with n.
- Forgetting a course that has no rules. Its count starts at 0, and it must be counted too.