⬅ Previous Topic
Course Schedule 2 - Task Ordering Using Topological SortNext Topic ⮕
Alien Dictionary Character Order⬅ Previous Topic
Course Schedule 2 - Task Ordering Using Topological SortNext Topic ⮕
Alien Dictionary Character OrderTopic Contents
In a directed graph with V
vertices and E
edges (represented as an adjacency list adj
), each node is uniquely labeled from 0
to V - 1
.
A node is called a terminal node if it has no outgoing edges. A node is a safe node if every possible path starting from that node eventually leads to a terminal node.
The task is to return a sorted list of all such safe nodes.
u → v
, add u
to revAdj[v]
.outDegree[]
array where each element is the number of outgoing edges from a node in the original graph.outDegree = 0
(terminal nodes).node
.neighbor
in revAdj[node]
:outDegree[neighbor]
by 1.outDegree[neighbor] == 0
, enqueue neighbor
.outDegree == 0
at the end are safe. Return them sorted.function eventualSafeNodes(adj) {
const V = adj.length;
const revAdj = Array.from({ length: V }, () => []);
const outDegree = Array(V).fill(0);
// Step 1: Build reversed graph and count out-degrees
for (let u = 0; u < V; u++) {
for (const v of adj[u]) {
revAdj[v].push(u);
outDegree[u]++;
}
}
const queue = [];
for (let i = 0; i < V; i++) {
if (outDegree[i] === 0) queue.push(i);
}
const safe = Array(V).fill(false);
while (queue.length) {
const node = queue.shift();
safe[node] = true;
for (const neighbor of revAdj[node]) {
outDegree[neighbor]--;
if (outDegree[neighbor] === 0) queue.push(neighbor);
}
}
const result = [];
for (let i = 0; i < V; i++) {
if (safe[i]) result.push(i);
}
return result;
}
// Example usage:
console.log(eventualSafeNodes([[1,2],[2,3],[5],[0],[5],[],[]])); // Output: [2,4,5,6]
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | Even in the best case (e.g., an acyclic graph), we must traverse all vertices and edges to identify safe nodes. |
Average Case | O(V + E) | Each node and edge is visited once, whether it's part of a cycle or not. |
Worst Case | O(V + E) | In graphs with deep chains or many dependencies, the traversal still touches all vertices and edges once. |
O(V + E)
Explanation: We store the reversed adjacency list, out-degree array, and queue, all of which depend on the number of vertices and edges.
⬅ Previous Topic
Course Schedule 2 - Task Ordering Using Topological SortNext Topic ⮕
Alien Dictionary Character OrderYou 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.