BackendML

Course Schedule II

Medium4 min read
The Course Schedule II problem requires finding a valid order in which to complete all courses, given a list of prerequisite relationships.

The goal is to return an ordering of courses that satisfies all prerequisites. If it is impossible to complete all courses because the prerequisite relationships contain a cycle, return an empty array.

Problem

You are given an integer numCourses, representing the total number of courses labeled from 0 to numCourses - 1, and a 2D array prerequisites, where prerequisites[i] = [a, b] means you must complete course b before taking course a.

Return an ordering of courses you should take to finish all courses. If there are multiple valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

Example 1

Input
numCourses = 2
prerequisites = [[1,0]]
Output
[0,1]
Explanation
To take course 1, you must first complete course 0. Therefore, the valid course order is [0,1].

Example 2

Input
numCourses = 4
prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output
[0,1,2,3]
Explanation
Course 0 must be completed before courses 1 and 2. Course 3 requires both courses 1 and 2 to be completed first. Therefore, [0,1,2,3] is a valid ordering.

Example 3

Input
numCourses = 2
prerequisites = [[1,0],[0,1]]
Output
[]
Explanation
Course 1 requires course 0, while course 0 requires course 1. This creates a cycle, making it impossible to complete all courses.

Solution

This problem can be solved using a Topological Sorting approach with Kahn's Algorithm, which uses a queue to process courses in an order that satisfies all prerequisite relationships.

The key observation is that a course with no remaining prerequisites can be completed immediately. We can repeatedly select such courses, add them to the result, and remove their prerequisite relationships from the graph.

First, we represent the courses as a directed graph. For every prerequisite pair [a, b], we add a directed edge from course b to course a. This indicates that course b must be completed before course a.

We also maintain an indegree array, where indegree[i] represents the number of prerequisites required for course i. Initially, every course with an indegree of 0 is added to a queue because it can be completed immediately.

Next, we process the queue: - Remove a course from the queue and add it to the result array.
- Visit all courses that depend on the completed course and decrease their indegree by 1.
- If a dependent course's indegree becomes 0, add it to the queue because all its prerequisites have been completed.

After processing the queue, we check how many courses were added to the result. If the result contains all numCourses courses, we return the ordering. Otherwise, some courses remain blocked by a cycle, so we return an empty array.

This approach works because every course is added to the result only after all its prerequisites have been processed. If a cycle exists, at least one course in that cycle will always have an unmet prerequisite, preventing all courses from being processed.
import java.util.*;

class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> graph = new ArrayList<>();
        int[] indegree = new int[numCourses];

        // Initialize the adjacency list
        for (int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<>());
        }

        // Build the graph and calculate indegrees
        for (int[] prerequisite : prerequisites) {
            int course = prerequisite[0];
            int prereq = prerequisite[1];

            graph.get(prereq).add(course);
            indegree[course]++;
        }

        Queue<Integer> queue = new LinkedList<>();

        // Add courses with no prerequisites
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] == 0) {
                queue.offer(i);
            }
        }

        int[] order = new int[numCourses];
        int index = 0;

        // Perform topological sorting
        while (!queue.isEmpty()) {
            int course = queue.poll();
            order[index++] = course;

            for (int nextCourse : graph.get(course)) {
                indegree[nextCourse]--;

                if (indegree[nextCourse] == 0) {
                    queue.offer(nextCourse);
                }
            }
        }

        // Check whether all courses can be completed
        if (index != numCourses) {
            return new int[0];
        }

        return order;
    }
}

Complexity

Let V represent the number of courses and E represent the number of prerequisite relationships.

We initialize the adjacency list and indegree array in O(V) time. Building the graph takes O(E) time. During topological sorting, each course is added to and removed from the queue at most once, and each prerequisite edge is processed once. Therefore, the overall time complexity is O(V + E).

The adjacency list requires O(V + E) space, while the indegree array, queue, and result array require O(V) space. Therefore, the overall space complexity is O(V + E).

Comments

No comments yet. Ask a question or share what helped.