01. Course Schedule II
β GFG solution to the Course Schedule II problem: find valid ordering of courses using topological sort with cycle detection. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given n courses, labeled from 0 to n - 1 and a 2D array prerequisites[][] where prerequisites[i] = [x, y] indicates that we need to take course y first if we want to take course x.
Find the ordering of courses we should take to complete all the courses.
Note: There may be multiple correct orders, you just need to return any one of them. If it is impossible to finish all tasks, return an empty array. The Driver code will print true if you return any correct order of courses else it will print false.
π Examples
Example 1
Input: n = 3, prerequisites[][] = [[1, 0], [2, 1]]
Output: true
Explanation: To take course 1, you must finish course 0. To take course 2, you must finish course 1.
So the only valid order is [0, 1, 2].Example 2
Input: n = 4, prerequisites[][] = [[2, 0], [2, 1], [3, 2]]
Output: true
Explanation: Course 2 requires both 0 and 1. Course 3 requires course 2.
Hence, both [0, 1, 2, 3] and [1, 0, 2, 3] are valid.π Constraints
$1 \le n \le 10^4$
$0 \le \text{prerequisites.size()} \le 10^5$
$0 \le \text{prerequisites}[i][0], \text{prerequisites}[i][1] < n$
All prerequisite pairs are unique
$\text{prerequisites}[i][0] \ne \text{prerequisites}[i][1]$
β
My Approach
The optimal approach uses Kahn's Algorithm (BFS-based Topological Sort) to find a valid course ordering:
Kahn's Algorithm (BFS Topological Sort)
Build Graph:
Create adjacency list representation where edge
[a, b]means coursebmust be completed before coursea.Calculate in-degree (number of prerequisites) for each course.
Initialize Queue:
Add all courses with in-degree
0(no prerequisites) to the queue.These courses can be taken immediately.
Process Courses:
Remove a course from queue and add it to the result order.
For each dependent course, decrease its in-degree by 1.
If in-degree becomes 0, add it to the queue (all prerequisites satisfied).
Cycle Detection:
If the result contains all
ncourses, a valid ordering exists.Otherwise, a cycle exists (impossible to complete all courses).
Return Result:
Return the complete ordering if valid, otherwise return an empty array.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(V + E), where V is the number of courses (vertices) and E is the number of prerequisite pairs (edges). Each course and prerequisite edge is processed exactly once during the BFS traversal.
Expected Auxiliary Space Complexity: O(V + E), as we store the adjacency list (O(E) space for edges), in-degree array (O(V) space), queue (O(V) space in worst case), and result array (O(V) space).
π§βπ» Code (C++)
class Solution {
public:
vector<int> findOrder(int n, vector<vector<int>>& prerequisites) {
vector<vector<int>> g(n);
vector<int> d(n);
for(auto& p : prerequisites) g[p[1]].push_back(p[0]), d[p[0]]++;
queue<int> q;
vector<int> r;
for(int i = 0; i < n; i++) if(!d[i]) q.push(i);
while(q.size()) {
int u = q.front(); q.pop(); r.push_back(u);
for(int v : g[u]) if(!--d[v]) q.push(v);
}
return r.size() == n ? r : vector<int>{};
}
};β Code (Java)
class Solution {
public ArrayList<Integer> findOrder(int n, int[][] pre) {
ArrayList<ArrayList<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) g.add(new ArrayList<>());
int[] d = new int[n];
for (int[] p : pre) g.get(p[1]).add(p[0]);
for (int[] p : pre) d[p[0]]++;
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; i++) if (d[i] == 0) q.add(i);
ArrayList<Integer> r = new ArrayList<>();
while (!q.isEmpty()) {
int u = q.poll(); r.add(u);
for (int v : g.get(u)) if (--d[v] == 0) q.add(v);
}
return r.size() == n ? r : new ArrayList<>();
}
}π Code (Python)
class Solution:
def findOrder(self, n, prerequisites):
g = [[] for _ in range(n)]
d = [0] * n
for a, b in prerequisites:
g[b].append(a)
d[a] += 1
q = [i for i in range(n) if d[i] == 0]
r = []
while q:
u = q.pop(0)
r.append(u)
for v in g[u]:
d[v] -= 1
if d[v] == 0: q.append(v)
return r if len(r) == n else []π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated