Course Schedule
Decide whether every course can be finished, by repeatedly taking a course whose prerequisites are done.
The problem
There are numCourses courses, numbered 0 to numCourses - 1. Each pair [a, b] in prerequisites means you must finish course b before you take course a. Return true if you can finish every course, and false if the rules make that impossible.
Input numCourses = 4, prerequisites = [[1, 0], [2, 1], [3, 1]]
Output true
Take 0 first, then 1, and then 2 and 3 in either order.
Input numCourses = 3, prerequisites = [[1, 0], [0, 2], [2, 1]]
Output false
1 needs 0, 0 needs 2 and 2 needs 1, so none of the three can ever be taken first.
Key constraint: Finishing is impossible exactly when the prerequisites contain a cycle, such as 1 needing 0 while 0 needs 1.
How to spot the pattern
- There are "do this before that" rules between tasks.
- You only need a yes or no: can every task be done in some order?
- A cycle in the rules is the only thing that can block you.
The idea
A course with no unfinished prerequisites can be taken right away, and taking it may free the courses that were waiting for it. So keep taking free courses, and for every course that depended on one, lower its count of missing prerequisites. Courses on a cycle wait for each other forever and never become free, so you can finish everything exactly when this process takes all numCourses courses.
Brute force: Repeatedly scan all courses for one whose prerequisites are all taken, which takes O(V * (V + E)) time.
Step by step
- 1Build a list from each course
bto the courses that need it, and count each course's prerequisites (its indegree). - 2Put every course with indegree 0 in a queue.
- 3Take a course from the queue, count it as taken and lower the indegree of every course that needs it.
- 4When a course's indegree drops to 0, add it to the queue.
- 5Return whether the number of taken courses equals
numCourses.
See the pattern move
The topological sort pattern on a small example. Step through it, or press play.
Code
from collections import deque
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
unlocks = [[] for _ in range(numCourses)] # course -> courses that need it first
indegree = [0] * numCourses # prerequisites each course still waits for
for course, before in prerequisites:
unlocks[before].append(course)
indegree[course] += 1
ready = deque(c for c in range(numCourses) if indegree[c] == 0)
taken = 0
while ready:
course = ready.popleft()
taken += 1
for dependent in unlocks[course]:
indegree[dependent] -= 1
if indegree[dependent] == 0:
ready.append(dependent)
# Courses on a cycle never reach indegree 0, so they are never taken.
return taken == numCoursesComplexity
Time
O(V + E)
Space
O(V + E)
V is the number of courses and E the number of pairs: each course enters the queue at most once and each pair is used once; the lists store every pair.
Watch out for
- Drawing the edge the wrong way:
[a, b]meansbcomes first, so the edge goes frombtoa. - Forgetting courses that appear in no pair; they have indegree 0 and still count as taken.
- Checking only that the queue emptied, instead of checking that every course was taken.
Follow-up questions
How would you detect the cycle with DFS instead?
Mark each course as unvisited, on the current path or done. Reaching a course that is still on the current path means there is a cycle, so the answer is false.
What if you also need an order to take the courses in?
Write down each course as you take it from the queue; that list is a valid order. That is Course Schedule II.
In Hinglish
Jin courses ka koi prerequisite baaki nahi, unhe queue mein daalo aur ek ek karke lo. Saare courses le paaye toh true, warna kahin cycle hai aur answer false.