Leetcode 207: Course Schedule

grid47
grid47
Exploring patterns and algorithms
Oct 17, 2024 7 min read

A calming flowchart with courses linking together, showing dependencies in a gentle, glowing path.
Solution to LeetCode 207: Course Schedule Problem

You are given a set of courses and a list of prerequisites. Each prerequisite is a pair of courses where the second course must be taken before the first one. Determine if it is possible to complete all courses based on these prerequisites. If there are cycles in the dependencies, it would be impossible to finish all courses.
Problem
Approach
Steps
Complexity
Input: You are given an integer numCourses representing the total number of courses and an array prerequisites where each element [a, b] indicates that course b must be completed before course a.
Example: numCourses = 3, prerequisites = [[1, 0], [2, 1]]
Constraints:
• 1 <= numCourses <= 2000
• 0 <= prerequisites.length <= 5000
• prerequisites[i].length == 2
• 0 <= ai, bi < numCourses
• All prerequisites pairs are unique.
Output: Return true if it is possible to finish all the courses. Otherwise, return false.
Example: Output: true
Constraints:
• The returned value must indicate whether it is possible to complete all courses given the prerequisites.
Goal: The goal is to determine if there is a cycle in the prerequisite graph. If there is no cycle, return true. If a cycle exists, return false.
Steps:
• Create a graph where each course points to its dependent courses.
• Use a counter to track the number of prerequisites for each course.
• Start with the courses that have no prerequisites and reduce the count of prerequisites for their dependent courses.
• If all courses can be completed (i.e., the prerequisite counter reaches zero for all), return true. Otherwise, return false if any course cannot be completed.
Goal: Ensure that the solution handles both small and large inputs efficiently.
Steps:
• The maximum number of courses is 2000.
• The maximum number of prerequisites is 5000.
• Courses are labeled with unique indices from 0 to numCourses - 1.
Assumptions:
• The input graph is well-formed with valid course numbers and prerequisites.
Input: Input: numCourses = 2, prerequisites = [[1, 0]]
Explanation: There are 2 courses. To take course 1, you must first take course 0. This is possible, so the output is true.

Input: Input: numCourses = 2, prerequisites = [[1, 0], [0, 1]]
Explanation: There are 2 courses. Course 1 requires course 0, and course 0 requires course 1. This forms a cycle, so it is impossible to complete all courses. The output is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus