Search
⌘K
Get Premium
Graphs

Course Schedule

medium

DESCRIPTION (inspired by Leetcode.com)

You have to take a total of numCourses courses, which are labeled from 0 to numCourses - 1. You are given a list of prerequisites pairs, where prerequisites[i] = [a, b] indicates that you must complete course b before course a.

Given the total number of courses and a list of prerequisite pairs, write a function to determine if it is possible to finish all courses.

Example 1:

Input:

numCourses = 3
prerequisites = [[1, 0], [2, 1]]

Output: true

Explanation: You can take courses in the following order: 0, 1, 2.

Example 2:

Input:

numCourses = 3
prerequisites = [[1, 0], [0, 1],[1,2]]

Output: false

Explanation: It is impossible to finish all courses, as you must finish course 1 before course 0 and course 0 before course 1.

Explanation

We can use the following approach to solve this problem:
  1. Start with a course that has no prerequisites.
  2. If that course is a prerequisite for another course, remove it from the prerequisites list.
  3. Now, Find the next course that has no prerequisites, and repeat the process.
When we can't find any more courses with no prerequisites, there are two possibilities:
  • If we have already taken all the courses, then we can return true.
  • Otherwise, we return false (as this means there was a circular dependency in the prerequisites).

Here's a visual representation of the above approach for the input numCourses = 4 and prerequisites = [[1,0],[2,1],[3,1],[2,3]]:
We've represented the input as a graph, where each node represents a course, and the edges represent the prerequisites between the courses.
3210
Start with Node 0
321
Remove Node 0 from the graph, and move to Node 1.
32
Remove Node 1 from the graph, and move to Node 3.
2
Remove Node 3 from the graph and move to Node 2.
At this point, there are no more courses without prerequisites, and we've visited all the courses. So, we can return true.

Cycle

Let's instead consider the input numCourses = 5 and prerequisites = [[1,0],[2,1],[3,2],[4,3],[1,4]]:
We start with Node 0, like before:
43210
Start with Node 0
But now, when we remove Node 0, we can't find any more courses without prerequisites!
4321
Remove Node 0. No nodes to choose from!
At this point, we've only processed 1 course, but there are still 4 courses left. So, we return false.

Topological Sort

The above approach is an application of Topological Sort. If we start by calculating the in-degree of each node, we can find the nodes with an in-degree of 0 and add them to a queue.
Next, while the queue is not empty, we remove a node from the queue. After removing a node, we decrement the in-degree of its neighbors. If any of the neighbors have an in-degree of 0, we add them to the queue.
Each time we remove a node from the queue, we increment a counter. When the queue is finally empty, we check if the counter is equal to the number of courses. If it is, we return true. Otherwise, we return false.
Solution
from collections import defaultdict, deque
class Solution:
def canFinish(self, numCourses, prerequisites):
graph = defaultdict(list)
in_degree = [0] * numCourses
for dest, src in prerequisites:
graph[src].append(dest)
in_degree[dest] += 1
queue = deque([i for i in range(numCourses) if in_degree[i] == 0])
count = 0
while queue:
course = queue.popleft()
count += 1
for neighbor in graph[course]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return count == numCourses
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(V + E) where V is the number of courses and E is the number of prerequisites. We visit each node and edge once.

Space Complexity: O(V + E) where V is the number of courses and E is the number of prerequisites. We store the graph as an adjacency list and the in-degree of each node.

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Reading Progress

On This Page