> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Find Eventual Safe States Python Solution

> Tested Python solution for LeetCode 802 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 802, [Medium](/catalog/medium). Topics: [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Graph Theory](/catalog/topics/graph-theory), [Topological Sort](/catalog/topics/topological-sort). [View on LeetCode](https://leetcode.com/problems/find-eventual-safe-states/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 802   # by problem number
lcpy gen -s find_eventual_safe_states   # by problem name
```

## 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]`.

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** (or another safe node).

Return *an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.*

### Examples

```
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
```

```
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
```

### Constraints

* n == graph.length
* 1 \<= n \<= 10^4
* 0 \<= graph\[i].length \<= n
* 0 \<= graph\[i]\[j] \<= n - 1
* graph\[i] is sorted in a strictly increasing order.
* The graph may contain self-loops.
* The number of edges in the graph will be in the range \[1, 4 \* 10^4].

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_eventual_safe_states/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_eventual_safe_states/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque


class Solution:
    # Time: O(n + e)
    # Space: O(n + e)
    def eventual_safe_nodes(self, graph: list[list[int]]) -> list[int]:
        n = len(graph)
        # Trim nodes in reverse topological order: a node is safe once all
        # its outgoing edges point at confirmed safe nodes
        out_degree = [len(edges) for edges in graph]
        reverse: list[list[int]] = [[] for _ in range(n)]
        for u, edges in enumerate(graph):
            for v in edges:
                reverse[v].append(u)

        queue = deque(i for i in range(n) if out_degree[i] == 0)
        safe = [False] * n
        while queue:
            v = queue.popleft()
            safe[v] = True
            for u in reverse[v]:
                out_degree[u] -= 1
                if out_degree[u] == 0:
                    queue.append(u)
        return [i for i in range(n) if safe[i]]
```

## Complexity

| Time | Space |
| - | - |
| O(n + e) | O(n + e) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.