Taro Logo

Course Schedule II

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+32
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.4K views
Topics:
GraphsDynamic Programming

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.

  • For example, the pair [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 <= 2000
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • ai != bi
  • All the pairs [ai, bi] are distinct.

Solution


Clarifying Questions

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:

  1. What is the range for the total number of courses, and can the prerequisites list be empty?
  2. If there are multiple valid topological orderings of the courses, does it matter which one I return, or is any valid ordering acceptable?
  3. Should we expect duplicate prerequisite pairs in the input list, and how should they be handled?
  4. What exact data structure should be returned if it is impossible to finish all courses due to a cycle (e.g., an empty array `[]`)?
  5. Are the course labels guaranteed to be strictly from `0` to `numCourses - 1`?

Brute Force Solution

Approach

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:

  1. Start by brainstorming every conceivable order in which you could possibly list all the classes.
  2. Take the first potential order from your list and examine the very first class on it.
  3. Check all the prerequisite rules to see if any class listed later in your sequence is supposed to happen before this first class.
  4. If you find a rule violation, cross this entire sequence off your list because it is invalid.
  5. If no rules are broken by the first class, move on to the second class in your sequence and repeat the rule check.
  6. Continue checking every single class in that sequence until you have verified the entire list.
  7. If a sequence makes it through every single rule without a single violation, you have successfully found a valid course schedule.
  8. If that sequence fails, simply throw it away and move on to test the next possible sequence on your master list until you find one that works.

Code Implementation

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 []

Big(O) Analysis

Time Complexity
–
Space Complexity
O(N) – To execute the brute force process of generating and verifying every conceivable order, we maintain auxiliary data structures proportional to the number of classes. Specifically, keeping track of the current sequence of classes and checking them against all prerequisite rules requires temporary lists and state-tracking variables whose memory footprint scales linearly with N, where N is the total number of courses. Additionally, evaluating the permutations on our master list demands extra storage for intermediate test sequences. Consequently, the total auxiliary memory grows in direct proportion to the input size N, simplifying to Big O notation as O(N).

Optimal Solution

Approach

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:

  1. Imagine every course as a point on a map, and every prerequisite rule as a one-way street pointing from the class you need to take first to the class you can take afterward.
  2. Count how many incoming streets point toward each course to keep track of how many prerequisites are blocking it.
  3. Find all the courses that have zero incoming streets pointing at them, meaning they are completely ready to be taken right now.
  4. Place one of these ready courses into your final schedule and pretend to erase it from the map along with all the one-way streets starting from it.
  5. Because you erased those streets, some new courses might suddenly have zero incoming streets left, making them newly ready.
  6. Keep repeating the process of grabbing ready courses, adding them to your schedule, and unlocking new ones until you run out of ready courses.
  7. If you successfully schedule every single course, you have your valid path, but if you get stuck with leftover courses that still have blocking streets, it means there is an impossible loop and no schedule is possible.

Code Implementation

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 []

Big(O) Analysis

Time Complexity
O(V + E) – The runtime is driven by visiting every course, represented as vertices V, and processing every prerequisite rule, represented as edges E. First, we iterate through all prerequisite pairs to build the graph and compute the incoming street counts for each vertex, which takes O(E) time. Next, we queue and process each of the V courses at most once, and for each course, we traverse its outgoing streets to decrement neighbor counts, taking O(V + E) operations in total. Summing these phases gives approximately V + E operations, which simplifies to Big O of V + E where V is the number of courses and E is the number of prerequisites.
Space Complexity
O(N + E) – To execute the scheduling process, we allocate an adjacency list to represent the one-way streets and an in-degree array to track incoming requirements for each of the N courses and E prerequisites. Additionally, the processing queue and the final schedule array each scale linearly to store up to N elements simultaneously. Summing these data structures together, the total auxiliary memory required grows proportionally with the total number of courses and prerequisites.

Edge Cases

Zero courses with no prerequisites
How to Handle:
Return a single-element array containing course zero since no dependencies exist.
Disconnected graph with multiple independent components
How to Handle:
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
How to Handle:
The topological sort detects the cycle and returns an empty array to indicate completion is impossible.
Duplicate prerequisite pairs in the input list
How to Handle:
Graph construction or degree calculation ignores duplicate edges to prevent incorrect in-degree counts.
Multiple valid topological orderings possible
How to Handle:
Any valid sequence that satisfies all prerequisite relationships is acceptable and returned.
Maximum number of courses with dense dependencies
How to Handle:
Using adjacency lists and in-degree tracking ensures linear time complexity of O(V + E) to prevent timeouts.
Deep linear chains of prerequisites
How to Handle:
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
How to Handle:
The cycle detection logic identifies the self-loop and immediately returns an empty array.
0/75 completed