⬅ Previous Topic
Course Schedule - Task Ordering with PrerequisitesNext Topic ⮕
Find Eventual Safe States in a Directed Graph⬅ Previous Topic
Course Schedule - Task Ordering with PrerequisitesNext Topic ⮕
Find Eventual Safe States in a Directed GraphTopic Contents
There are N tasks, labeled from 0
to N-1
. Some tasks have prerequisites, meaning a task must be done only after another task is completed. These dependencies are given as pairs [a, b]
meaning b
must be done before a
.
The goal is to return an ordering of tasks that satisfies all the prerequisites. If no valid ordering exists (due to a cycle), return an empty array.
This is a classic case of Topological Sorting in a Directed Graph.
graph
and an array indegree
to count prerequisites for each node.indegree = 0
.function findOrder(numCourses, prerequisites) {
const graph = Array.from({ length: numCourses }, () => []);
const indegree = Array(numCourses).fill(0);
for (const [a, b] of prerequisites) {
graph[b].push(a);
indegree[a]++;
}
const queue = [];
for (let i = 0; i < numCourses; i++) {
if (indegree[i] === 0) queue.push(i);
}
const result = [];
while (queue.length > 0) {
const course = queue.shift();
result.push(course);
for (const neighbor of graph[course]) {
indegree[neighbor]--;
if (indegree[neighbor] === 0) queue.push(neighbor);
}
}
return result.length === numCourses ? result : [];
}
console.log(findOrder(4, [[1,0],[2,0],[3,1],[3,2]])); // [0,1,2,3] or [0,2,1,3]
console.log(findOrder(2, [[0,1],[1,0]])); // [] due to cycle
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | In the best case, we visit all vertices and edges once — one pass for building the graph and one pass for processing the queue. |
Average Case | O(V + E) | Regardless of prerequisites distribution, all vertices and edges are still processed once each. |
Worst Case | O(V + E) | Even with dense dependencies or cycles, we process each vertex and edge exactly once in topological sort. |
O(V + E)
Explanation: We use space for the adjacency list (O(E)), the indegree array (O(V)), the queue (up to O(V)), and the result list (O(V)).
⬅ Previous Topic
Course Schedule - Task Ordering with PrerequisitesNext Topic ⮕
Find Eventual Safe States in a Directed GraphYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.