Learn DSA
Depth-First Search
Greedy Algorithms
Course Schedule
DESCRIPTION (credit 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:
Output: true
Explanation: You can take courses in the following order: 0, 1, 2.
Example 2:
Input:
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.
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
"There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. Some courses may have prerequisites, for example, to take course `0` you have to first take course `1`, which is expressed as a pair: `[0, 1]`. Given the total number of courses and a list of prerequisite pairs, determine if it is possible for you to finish all courses."
Run your code to see results here
Have suggestions or found something wrong?
Explanation
- Start with a course that has no prerequisites.
- If that course is a prerequisite for another course, remove it from the prerequisites list.
- Now, Find the next course that has no prerequisites, and repeat the process.
- 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).
Cycle
Topological Sort
from collections import defaultdict, dequeclass Solution:def canFinish(self, numCourses, prerequisites):graph = defaultdict(list)in_degree = [0] * numCoursesfor dest, src in prerequisites:graph[src].append(dest)in_degree[dest] += 1queue = deque([i for i in range(numCourses) if in_degree[i] == 0])courses_taken = 0while queue:course = queue.popleft()courses_taken += 1for neighbor in graph[course]:in_degree[neighbor] -= 1if in_degree[neighbor] == 0:queue.append(neighbor)return courses_taken == numCourses
Complexity Analysis
Login to track your progress
Your account is free and you can post anonymously if you choose.