Taro Logo

Course Schedule

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+30
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
1.9K views
Topics:
GraphsRecursion

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 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 <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • All the pairs prerequisites[i] are unique.

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. Can there be duplicate prerequisite pairs in the input list, and how should they be handled if present?
  2. What should be returned if `numCourses` is 0 or if the prerequisites list is empty?
  3. Can a course have a prerequisite of itself (i.e., a self-loop like `[i, i]`), and if so, does that automatically mean we cannot finish all courses?
  4. Are the course labels guaranteed to be from 0 to `numCourses - 1`, or could there be out-of-range indices or non-contiguous numbering?
  5. Can there be multiple disconnected components in the prerequisite graph?

Brute Force Solution

Approach

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:

  1. Start by picking any class from your list that does not have any prerequisites.
  2. Pretend to take that class, and then look for another class that has all its prerequisites met.
  3. Continue this process of picking available classes one by one until you have either successfully listed all the classes or you get completely stuck.
  4. If you successfully list all the classes without getting stuck, then it is possible to finish everything.
  5. If you get stuck because every remaining class requires something you have not taken yet, erase your progress and start over.
  6. Try a completely different starting class and repeat the entire exploration process from the beginning.
  7. Keep trying different paths until you either find a successful way to take all the classes or you run out of new paths to test.

Code Implementation

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 True

Big(O) Analysis

Time Complexity
O(n * m) – For each of the n total classes, we might need to explore every possible starting path and restart multiple times when getting stuck. In the worst-case scenario of exploring different paths involving m prerequisite relationships, we repeatedly check available classes and dependencies across multiple attempts. This leads to approximately n * (n + m) operations when factoring in the repeated paths and prerequisite checks, which simplifies to O(n * m).
Space Complexity
O(N + E) – To analyze the auxiliary space complexity, let N be the number of courses and E be the number of prerequisite relationships. The algorithm requires an adjacency list to represent the course dependencies, which stores all N courses and E edges. Additionally, we use a visited status array or hash map of size N to track the exploration state of each course and a recursion stack or queue that can grow up to a depth of N. Therefore, the extra memory required scales linearly with the total number of courses and their dependencies combined.

Optimal Solution

Approach

To 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:

  1. Map out all the courses and their specific prerequisites so you can see which classes depend on others.
  2. Count how many prerequisites each individual course needs before you are allowed to take it.
  3. Find any course that currently has zero prerequisites standing in its way.
  4. Take that zero-prerequisite course and pretend you have completed it.
  5. Because you finished that course, update the remaining classes by crossing that course off their list of prerequisites.
  6. Repeat the process of finding newly unlocked courses that now have zero prerequisites left.
  7. If you successfully manage to take every single course, then the schedule is possible. However, if you get stuck with remaining courses that all still require prerequisites, it means you are trapped in a circular block and cannot finish.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(V + E) – To analyze the time complexity, let V represent the number of courses and E represent the number of prerequisite pairs. Building the adjacency list and counting the initial prerequisites requires iterating through all the prerequisite pairs, taking O(E) time. Next, our process pushes and pops each course from a queue at most once, and for each course, we traverse its outgoing edges, which accounts for processing every course (V) and every dependency (E) exactly once. Summing these operations together yields roughly V + E total steps, which simplifies cleanly to Big O of V plus E.
Space Complexity
O(V + E) – To determine if all courses can be completed, we utilize auxiliary data structures including an adjacency list to map the dependencies and an in-degree array to track the remaining prerequisite counts for each course. Additionally, a queue is used to process the nodes with zero prerequisites, which in the worst case can hold all V courses simultaneously. Across both the graph representation and the tracking array, the extra memory scales linearly with the number of courses V and the total number of prerequisites E.

Edge Cases

Zero prerequisites given an arbitrary number of courses
How to Handle:
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
How to Handle:
The loop executes once with numCourses equal to 1, validating the graph has no cycles and returning true.
Direct cycle between two courses
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Using an iterative BFS approach with in-degree counts avoids stack overflow issues that could occur with deep DFS recursion.
0/75 completed