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 the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
Example 2:
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
Example 3:
Input: numCourses = 1, prerequisites = [] Output: [0]
Constraints:
1 <= numCourses <= 20000 <= prerequisites.length <= numCourses * (numCourses - 1)prerequisites[i].length == 20 <= ai, bi < numCoursesai != bi[ai, bi] are distinct.When 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 need to figure out the right order to take a list of classes, where some classes must be finished before others can start. The brute force approach involves writing down every single possible sequence of classes and then testing each one to see if it breaks any of the prerequisite rules.
Here's how the algorithm would work step-by-step:
import itertools
def find_order(num_courses, prerequisites):
all_courses = range(num_courses)
# Generate every conceivable sequence of courses to evaluate all possible schedules
for schedule_permutation in itertools.permutations(all_courses):
is_schedule_valid = True
for current_index in range(len(schedule_permutation)):
course = schedule_permutation[current_index]
for prerequisite in prerequisites:
target_course, prereq_course = prerequisite
if course == prereq_course:
for future_index in range(current_index + 1, len(schedule_permutation)):
if schedule_permutation[future_index] == target_course:
is_schedule_valid = False
break
if not is_schedule_valid:
break
if not is_schedule_valid:
break
# Stop checking permutations immediately once the first valid schedule is found
if is_schedule_valid:
return list(schedule_permutation)
# Return an empty list if no valid course order exists after checking every permutation
return []To figure out the correct order to take courses, we can think of this like putting together a puzzle where certain pieces must come before others. The best strategy is to constantly look for courses that have no remaining prerequisites, take them, and then unlock the next set of courses until we have a complete path.
Here's how the algorithm would work step-by-step:
def find_order(total_courses, prerequisites): incoming_edge_counts = [0] * total_courses adjacency_list = [[] for _ in range(total_courses)] for target_course, required_course in prerequisites: adjacency_list[required_course].append(target_course) incoming_edge_counts[target_course] += 1 # We start with courses that have no prerequisites to kickstart the scheduling. ready_courses_queue = [] for course_index in range(total_courses): if incoming_edge_counts[course_index] == 0: ready_courses_queue.append(course_index) complete_schedule = [] while ready_courses_queue: current_course = ready_courses_queue.pop(0) complete_schedule.append(current_course) for dependent_course in adjacency_list[current_course]: incoming_edge_counts[dependent_course] -= 1 if incoming_edge_counts[dependent_course] == 0: ready_courses_queue.append(dependent_course) # If all courses are scheduled, return the path; otherwise, a cycle exists. if len(complete_schedule) == total_courses: return complete_schedule return []| Case | How to Handle |
|---|---|
| Zero courses with no prerequisites | Return a single-element array containing course zero since no dependencies exist. |
| Disconnected graph with multiple independent components | The Kahn or DFS algorithm processes all nodes regardless of whether they are connected, ensuring all courses are included in the result. |
| Direct or indirect cycles present in the prerequisite graph | The topological sort detects the cycle and returns an empty array to indicate completion is impossible. |
| Duplicate prerequisite pairs in the input list | Graph construction or degree calculation ignores duplicate edges to prevent incorrect in-degree counts. |
| Multiple valid topological orderings possible | Any valid sequence that satisfies all prerequisite relationships is acceptable and returned. |
| Maximum number of courses with dense dependencies | Using adjacency lists and in-degree tracking ensures linear time complexity of O(V + E) to prevent timeouts. |
| Deep linear chains of prerequisites | An iterative BFS Kahn's algorithm avoids recursion stack overflow issues that would occur in a purely recursive DFS approach. |
| Self-dependency where a course requires itself | The cycle detection logic identifies the self-loop and immediately returns an empty array. |