Course Schedule
There are a total of numCourses
courses you have to take,
labeled from 0
to numCourses - 1
.
You are given an array prerequisites
where prerequisites[i] = [y, x]
indicates that you must take course x
first if you want to take course y
.
Return true
if you can finish all courses, or false
otherwise.
Function Signature:
from typing import List
def can_finish_courses(numCourses: int, prerequisites: List[List[int]]) -> bool:
"""
Determine if it is possible to finish all courses based on prerequisites.
Parameters:
- numCourses: The total number of courses.
- prerequisites: A list of prerequisites, where prerequisites[i] = [a, b]
indicates that you must take course b first if you want to take course a.
Returns:
- bool: True if it is possible to finish all courses, False otherwise.
"""
# Your code here
Example:
# Input: numCourses = 2, prerequisites = [[1,0]]
# Output: True
# Explanation: There are a total of 2 courses to take. To take course 1 you should
# have finished course 0. So it is possible.
# Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
# Output: False
# Explanation: There are a total of 2 courses to take. To take course 1 you should
# have finished course 0, and to take course 0 you should also have finished course 1.
# So it is impossible.
# Input: numCourses = 4, prerequisites = [[1, 0], [2, 1], [2, 3], [3, 0]]
# Output: True
# Explanation: There are a total of 4 courses available. We can start by taking
# course 0, which will then enable us to take courses 1 and 3.
# Once we have completed courses 1 and 3, we can proceed to take course 2.
# Therefore, it is indeed possible to complete all the courses.
Note:
- The input prerequisites are a graph represented by a list of edges, not adjacency matrices.
- You may assume that there are no duplicate edges in the input prerequisites.
Instructions:
- Write the
can_finish_courses
function to solve the problem. - Implement your solution in Python.
- Provide clear comments in your code.
- Discuss the time and space complexity of your solution.
As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊