Course Schedule II (Topological Sort) - Leetcode Solution


💡 Step-by-Step Thought Process

  1. Understand the problem: Find a valid order to take all courses given prerequisites, returning an empty list if impossible.
  2. Create an adjacency list using a defaultdict to store the graph, where each course maps to its prerequisites.
  3. Initialize an empty list order to store the course order.
  4. Initialize a states array with UNVISITED (0) for each course to track visit status.
  5. Define a DFS function that takes a node (course) and returns False if a cycle is detected, True otherwise.
  6. In DFS, if the node is VISITING (1), a cycle is detected, return False.
  7. If the node is VISITED (2), return True as it’s already processed.
  8. Mark the node as VISITING, then recursively check all its neighbors (prerequisites).
  9. If any neighbor returns False, return False.
  10. Mark the node as VISITED, append it to order, and return True.
  11. Run DFS for each course; if any returns False, return an empty list.
  12. Return the order list.

Code Solution


                

                

                

                

Detailed Explanation

What Is the Course Schedule II Problem?

The Course Schedule II problem asks you to return a valid order in which to complete all courses given a list of prerequisites. If it’s impossible to complete all courses due to a cycle in the course dependencies, return an empty list.

Topological Sort Approach for Course Scheduling

This problem is a classic application of topological sorting in a directed graph. Each course is a node, and each prerequisite is a directed edge. To solve this, we use depth-first search (DFS) to build a valid course order and detect cycles.

How to Solve Course Schedule II Using DFS

Here is a step-by-step breakdown of how to solve the problem using DFS and a cycle detection strategy:

  • Use a hash map to build an adjacency list from the prerequisites.
  • Track each course’s visit state with an array: UNVISITED (0), VISITING (1), and VISITED (2).
  • Perform DFS traversal for each course:
    • If the course is VISITING again, a cycle exists → return False.
    • If the course is VISITED, return True to avoid redundant work.
    • Mark the course as VISITING and recursively visit all prerequisites.
    • Once all neighbors are explored, mark the course as VISITED and append it to the course order.
  • Reverse the result list to get the correct topological sort order.

Why Topological Sorting Works for Course Prerequisites

In a valid course order, all prerequisites must appear before the dependent course. Using post-order traversal during DFS naturally builds this order. Reversing the result ensures each course comes after its dependencies. If a cycle is found, we can’t finish all courses, and we return an empty list.

Time and Space Complexity of the Solution

Time Complexity: O(V + E), where V is the number of courses and E is the number of prerequisites. Each node and edge is visited once.
Space Complexity: O(V + E), due to the adjacency list and recursive call stack.

Conclusion: Solving Course Schedule II Efficiently

The DFS-based topological sort is an efficient way to solve the Course Schedule II problem. It detects cycles in course prerequisites and builds a valid course completion order. This approach is scalable, fast, and leverages key graph theory principles used in many scheduling and dependency resolution problems.

Get Personalized Support at AlgoMap Bootcamp 💡