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] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
[0, 1], indicates that to take course 0 you have to first take course 1.Return true if you can finish all courses. Otherwise, return false.
Example 1:
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.
Example 2:
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.
Constraints:
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCoursesWhen you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a list of classes you need to take, but some classes require you to take other classes first. The brute force approach involves exploring every possible order in which you could try to take all the classes to see if a valid path exists.
Here's how the algorithm would work step-by-step:
def can_finish(num_courses, prerequisites):
adjacency_list = [[] for course_index in range(num_courses)]
for target_course, prereq_course in prerequisites:
adjacency_list[target_course].append(prereq_course)
def explore_paths(current_course, visited_set, current_path):
# A cycle means we are stuck in a circular dependency and cannot finish
if current_course in current_path:
return False
if current_course in visited_set:
return True
current_path.add(current_course)
for required_course in adjacency_list[current_course]:
if not explore_paths(required_course, visited_set, current_path):
return False
current_path.remove(current_course)
visited_set.add(current_course)
return True
global_visited = set()
# We test every possible starting course to see if a valid schedule exists
for starting_course in range(num_courses):
if starting_course not in global_visited:
path_tracker = set()
if not explore_paths(starting_course, global_visited, path_tracker):
return False
# If all courses are checked without cycles, then finishing is possible
return TrueTo figure out if you can finish all your courses, we can think of this like planning a chain of prerequisites where some tasks must happen before others. The optimal strategy looks for a starting point with no prerequisites, finishes it, and then removes it from our list to unlock the next set of courses.
Here's how the algorithm would work step-by-step:
def can_finish(total_courses, prerequisite_pairs):
adjacency_list = [[] for _ in range(total_courses)]
in_degree_counts = [0] * total_courses
for course, prerequisite in prerequisite_pairs:
adjacency_list[prerequisite].append(course)
in_degree_counts[course] += 1
# Identify courses with no prerequisites as safe starting points to begin processing.
ready_courses_queue = []
for course_index in range(total_courses):
if in_degree_counts[course_index] == 0:
ready_courses_queue.append(course_index)
completed_course_count = 0
while ready_courses_queue:
current_course = ready_courses_queue.pop(0)
completed_course_count += 1
# Decrement prerequisite counts for dependent courses as their blockers are completed.
for dependent_course in adjacency_list[current_course]:
in_degree_counts[dependent_course] -= 1
if in_degree_counts[dependent_course] == 0:
ready_courses_queue.append(dependent_course)
# Verify if all courses were successfully processed without encountering a circular dependency.
return completed_course_count == total_courses| Case | How to Handle |
|---|---|
| Zero prerequisites given an arbitrary number of courses | The adjacency list will be empty and the algorithm will process all nodes with in-degree zero successfully returning true. |
| Single course with no prerequisites | The loop executes once with numCourses equal to 1, validating the graph has no cycles and returning true. |
| Direct cycle between two courses | The graph traversal will detect a back-edge pointing to a node currently in the recursion stack, immediately returning false. |
| Self-loop prerequisite where a course depends on itself | The prerequisite pair where course A requires course A will be detected as a cycle during graph traversal and return false. |
| Disconnected graph components with multiple valid or invalid paths | The algorithm iterates through all nodes from 0 to numCourses - 1 to ensure every disconnected component is fully explored. |
| Maximum possible number of courses and dense prerequisite edges | Using an efficient adjacency list representation and Kahn's algorithm or DFS with memoization ensures optimal time complexity without exceeding memory limits. |
| Duplicate prerequisite pairs in the input list | Building the adjacency list will result in duplicate edges which do not affect cycle detection correctness but should be handled efficiently. |
| Deep linear chains of prerequisites causing deep recursion | Using an iterative BFS approach with in-degree counts avoids stack overflow issues that could occur with deep DFS recursion. |