Find Eventual Safe States
Topological Sort DSA practice problem on Onlearn.
Difficulty: hard.
Topics: Find all eventual safe nodes in a directed graph using adjacency list, Graph, Directed Graph, Adjacency List, Graph Traversal, Breadth-First Search, Topological Sorting, Cycle Detection, Queue, Sorting, Time Complexity, Space Complexity, topological sort, tree properties, graph algorithms, graph traversal, graph properties, cycle detection, bfs, Graph Terminology, Directed Acyclic Graph (DAG), Strongly Connected Components (Kosaraju's).
A directed graph of V vertices and E edges is given in the form of an adjacency list adj. Each node of the graph is labeled with a distinct integer in the range 0 to V 1. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node. You have to return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order. Input Specification: The first line contains two integers, V and E, representing the number of vertices and edges, respectively. The following E lines each contain two integers u and v, representing a directed edge from u to v. Output Specification: Return an array of integers representing the safe nodes, sorted in ascending order. Example 1: Input: V = 7, E = 7 Adjacency List: 0: [1, 2] 1: [3, 2] 2: [5] 3: [0] 4: [5] 5: [] 6: [] Output: [2, 4, 5, 6] Explanation: Here terminal nodes are 5 and 6 as they have no outgoing edges. From node 0: two paths are there 0 2 5 and 0 1 3 0. The second path does not end at a terminal node. So it is not a safe node. From node 1: two paths exist: 1 3 0 1 and 1 2 5. But the first one does not end at a terminal node. So it is not a safe node. From node 2: only one path: 2 5 and 5 is a terminal node. So it is a safe node. From node 3: two paths: 3 0 1 3 and 3 0 2 5 but the first path does not end at a terminal node. So it is not a safe node. From node 4: Only one path: 4 5 and 5 is a terminal node. So it is also a safe node. From node 5: It is a terminal node. So it is a safe node as well. From node 6: It is a terminal node. So it is a safe node as well. Example 2: Input: V = 4, E = 4 Adjacency List: 0: [1] 1: [2] 2: [0] 3: [] Output: [3] Explanation: Node 3 itself is a terminal node and it is a safe node as well. But all the paths from other nodes do not lead to a terminal node. So they are excluded from the answer.