207. Course Schedule

Description

See: https://leetcode.com/problems/course-schedule/

Solution

This is a graph question. To be a valid course schedule the graph will need to be a directed acycle graph (DAG). If a cycle is found then the course schedule is NOT valid.

There are two solutions to this problem:

DFS Solution

DFS tranversal can be used to walk the graph and detect any cycles. The DFS algorithm is modified to keep track of the status of a vertex. The statuses are:

  • Not visited

  • Processing

  • Processed

Invalid Course Schedule

When traversing the graph, if a vertex is found to be in "Processing" status then a cycle has been detected.

For example, assume the following class schedule [[0, 1], [1, 0]]. Here the class schedule says:

  • class 0 has a prerequisite of class 1

  • class 1 has a prerequisite of class 0

So, there is a cycle. When traversing the graph, we will visit vertex 0, traverse to vertex 1 and then back to vertex 0. Because vertex 0 is in status "processing" a cycle is detected.

Now we are in a cycle because course 1 has a prerequisite of course 0 (which is in status "processing"). So the algorithm can stop because we now know the course schedule is invalid.

Valid Course Schedule

If the algorithm does not encounter any vertices with "processing" status, then there are not cycles and the course schedule is valid.

Example: assume the following course schedule: [[0,1], [1,2]]. This means:

  • Course 0 has a prerequisite of Course 1

  • Course 1 has a prerequisite of Course 2

Here there are no cycles. So, when following the edges from a vertex we will not encounter a vertex in "processing status". If we come across a vertex that has status "processed" then we can skip it. We have already traversed it and found it to be valid. So there is no point in processing it again.

Algorithm

Kahn's Algorithm Solution

Kahn's Algorithm can also be used to detect a valid course schedule.

Last updated