LeetCode 207: Course Schedule

Problem Description

Explanation

To solve this problem, we can model the courses and prerequisites as a graph where each course is a node and each prerequisite relationship is a directed edge. We need to check if there is a cycle in the graph, as a cycle would indicate a situation where it is impossible to complete all courses.

We can use a topological sorting algorithm, specifically Kahn's algorithm, to detect cycles in a directed graph. The key idea is to iteratively remove nodes with zero in-degree (no prerequisites) from the graph, updating the in-degrees of remaining nodes. If at the end all nodes have been removed, then there is no cycle and it is possible to complete all courses.

Algorithm:

  1. Create an adjacency list representation of the graph using the prerequisites array.
  2. Initialize an array inDegrees to store the in-degree of each course.
  3. Initialize a queue and add all courses with in-degree 0 to the queue.
  4. While the queue is not empty, remove a course from the queue, decrement the in-degrees of its neighbors, and if any neighbor's in-degree becomes 0, add it to the queue.
  5. After processing all courses, if the count of courses processed is equal to numCourses, return true (no cycles). Otherwise, return false.

Time Complexity:

The time complexity of this algorithm is O(V + E), where V is the number of courses (vertices) and E is the number of prerequisites (edges).

Space Complexity:

The space complexity is O(V + E) as well, considering the adjacency list and inDegrees array.

Solutions

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<List<Integer>> graph = new ArrayList<>();
        int[] inDegrees = new int[numCourses];
        
        for (int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<>());
        }
        
        for (int[] pre : prerequisites) {
            graph.get(pre[1]).add(pre[0]);
            inDegrees[pre[0]]++;
        }
        
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (inDegrees[i] == 0) {
                queue.offer(i);
            }
        }
        
        int count = 0;
        while (!queue.isEmpty()) {
            int course = queue.poll();
            count++;
            for (int neighbor : graph.get(course)) {
                inDegrees[neighbor]--;
                if (inDegrees[neighbor] == 0) {
                    queue.offer(neighbor);
                }
            }
        }
        
        return count == numCourses;
    }
}

Loading editor...