682. Safe Starting Points

A warehouse robot moves along one-way conveyor links between n stations numbered 0 to n - 1. The array graph describes the network: graph[i] lists the stations reachable in one step from station i. A row may be empty (a dead-end dock), and may contain repeated values or i itself.

At every station the robot picks any outgoing link it likes. A station is safe if, whatever links are chosen, the robot is guaranteed to reach a dead-end dock after finitely many steps. A dead-end dock is itself safe. Return all safe stations in increasing order, or an empty array if none exists.

Solve it in O(n + m) time, where m is the total number of links.

Example 1

Input:
graph = [[1],[2],[0,3],[],[3,5],[6],[]]
Output:
[3,4,5,6]
Explanation:

Stations 0, 1 and 2 can circle forever, so they are unsafe; stations 3 to 6 always end at dead-end dock 3 or 6.

Example 2

Input:
graph = [[],[0],[1],[2]]
Output:
[0,1,2,3]
Explanation:

Every station leads down a single line to the dead end at station 0, so all four are safe.

Constraints

1 ≤ n ≤ 20000

0 ≤ graph[i].length ≤ n and the total number of links is at most 40000

0 ≤ graph[i][j] < n; links may repeat and may point back to i

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O(n + m)
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…