Course Schedule

Course Schedule Problem of Graphs – Hard Level Problem

You are given an array prerequisites, where each element prerequisites[i] = [a, b] means you must complete course b before taking course a.

For example, [0, 1] indicates that course 1 must be completed before course 0.

There are a total of numCourses, labeled from 0 to numCourses – 1. Return true if it is possible to complete all courses; otherwise, return false.

Course Schedule

Explanation: First take course 1 (no prerequisites) and then take course 0.

Explanation: In order to take course 1 you must take course 0, and to take course 0 you must take course 1. So it is impossible.

Constraints :

  • 1 <= numCourses <= 1000
  • 0 <= prerequisites.length <= 1000
  • All prerequisite pairs are unique.

Course Schedule Solution of Graphs

Recommendation for Time and Space Complexity – Aim for a solution with O(V + E) time and space, where V is the number of courses (nodes) and E is the number of prerequisites (edges).

Hints for solving problems

Hint 1

Think of courses as nodes and prerequisites as directed edges in a graph. The goal is to check if the graph has a cycle. If there’s a cycle, it’s impossible to finish all courses. Can you use an algorithm to detect cycles in a graph?

Hint 2

Use DFS to detect cycles. For each course, run a DFS and try to complete its prerequisites by visiting its neighbors. Track the nodes in the current DFS call using a hash set (path). If you revisit a node already in path, a cycle is detected.

Hint 3

Start DFS for each course, using a hash set (path) to track nodes in the current call. If a node is revisited, it indicates a cycle, and we return false. Once DFS for a course finishes with no cycle, clear its neighbors to avoid redundant checks.

There are mainly 2 approach to solve this problem-

  1. Cycle Detection(DFS) Method
  2. Topological Sort (Kahn’s Algorithm) Method

1. Cycle Detection(DFS) Method

Treat the courses as a graph and use DFS to detect cycles. Maintain a visited set to track the current path during DFS. If a course is revisited in the same path, a cycle exists, making it impossible to complete all courses.

  • Time complexity: O(V + E)
  • Space complexity: O(V + E)

where V is the number of courses and E is the number of prerequisites.

Code

2. Topological Sort (Kahn’s Algorithm) Method

Use Kahn’s Algorithm to perform a topological sort. Start with courses that have no prerequisites (in-degree 0) and process them iteratively, reducing the in-degree of their neighbors. If all courses are processed, it’s possible to complete them; otherwise, a cycle exists.

  • Time complexity: O(V + E)
  • Space complexity: O(V + E)

where V is the number of courses and E is the number of prerequisites.

Code

More Articles