Find Eventual Safe States — LeetCode 802 Python Solution

MediumDepth-First SearchBreadth-First SearchGraphTopological Sort
Problem
#802
Reading time
3 min

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

Python
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

MeasureComplexity
TimeO(V+E)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview