Find Eventual Safe States — LeetCode 802 Python Solution
- Problem
- #802
- Pattern
- Topological Sort
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
Example
- Input
- graph = [[1,2],[2,3],[5],[0],[5],[],[]]
- Output
- [2,4,5,6]
- Explanation
- The given graph is shown above.
Python solution
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
rg = defaultdict(list)
indeg = [0] * len(graph)
for i, vs in enumerate(graph):
for j in vs:
rg[j].append(i)
indeg[i] = len(vs)
q = deque([i for i, v in enumerate(indeg) if v == 0])
while q:
i = q.popleft()
for j in rg[i]:
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
return [i for i, v in enumerate(indeg) if v == 0]Complexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 802. Find Eventual Safe States is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 802. Find Eventual Safe States?
- LeetCode 802. Find Eventual Safe States is rated Medium on LeetCode.
- What is the time complexity of LeetCode 802. Find Eventual Safe States?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 802. Find Eventual Safe States?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 802. Find Eventual Safe States cover?
- LeetCode 802. Find Eventual Safe States is tagged Depth-First Search, Breadth-First Search, Graph and Topological Sort on LeetCode.