AlgoMaster Logo

Course Schedule II

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. DFS-Based Topological Sorting

The problem of finding an order of courses to take based on prerequisites can be represented as finding a topological sort of a directed graph. Here, each course is a node, and each prerequisite relationship is a directed edge between two nodes.

Intuition:

  1. Graph Representation: We represent our courses as nodes and prerequisites as directed edges between these nodes.
  2. DFS for Cycle Detection and Ordering: Perform DFS to detect cycles in the graph and to help build the ordering of the courses. If we detect a cycle, it's impossible to complete all courses.
  3. Topological Sort: As we exit the DFS for a node, it's added to the ordering stack/list, ensuring that prerequisites come first before the courses that depend on them.

Steps:

  • Construct a graph using adjacency list representation.
  • Use a visited list to track the visit status of nodes: unvisited, visiting, or visited.
  • Use a stack to assist in constructing the topological order.

Code:

2. Kahn’s Algorithm (BFS-Based Topological Sorting)

Intuition:

  1. In-Degree Calculation: Calculate the in-degree for each node (number of prerequisites for each course).
  2. Queue Processing: Use a queue to process nodes with in-degree of 0 (no prerequisites).
  3. Order Construction: Gradually build the order of courses by removing nodes from the queue and adjusting in-degrees, adding new nodes with in-degree 0 to the queue.

Steps:

  • Construct the graph and compute in-degrees for each course.
  • Use a queue to perform a level-by-level traversal, akin to BFS.
  • Track the order and check if all nodes (courses) are processed.

Code: