oneby7

Graphs Topological sort

459. Find Eventual Safe States

Medium

You are given a directed graph with n nodes, numbered from 0 to n - 1. graph[i] lists the nodes that node i has an edge to. An edge can be followed only in its own direction, from i to a node in graph[i].

A node is terminal if no edge leaves it, so its list is empty. A node is safe if every path that starts at it ends at a terminal node. A path that can go round a cycle keeps going for ever and never ends, so a node where such a path starts is not safe. A terminal node is safe, since every path from it ends at once.

Return all the safe nodes in ascending order.

Example 1

0123456

Input: graph = [[1, 4], [2], [3], [], [5], [4], [3]]

Output: [1,2,3,6]

Explanation: Node 3 is terminal. Nodes 1, 2 and 6 lead only to node 3, so they are safe. Nodes 4 and 5 point to each other for ever. Node 0 is not safe: one path goes to 1 and ends, but another goes to 4 and never ends.

Example 2

012

Input: graph = [[0, 1], [2], []]

Output: [1,2]

Explanation: Node 0 has an edge to itself, so a path from 0 can stay at 0 for ever. Nodes 1 and 2 lead only to the terminal node 2.

Example 3

0123

Input: graph = [[1], [2], [0], [0]]

Output: []

Explanation: There is no terminal node. Nodes 0, 1 and 2 form a cycle, and node 3 leads into it, so no node is safe.

Check your understanding

Work out the answer for this input before you write any code.

graph = [[1, 4], [2], [3], [1], [], [0]]

Constraints

  • 1 ≤ n == graph.length ≤ 105
  • 0 ≤ graph[i][j] < n
  • The values in each graph[i] are distinct, in any order. graph[i] may contain i itself.
  • All the lists together hold at most 2 × 105 edges.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.