Problem 508574 · medium · Phase 05 Advanced Algorithms & Graphs

Nodes That Cannot Reach a Cycle

topological sort · reverse graph · cycle detection

A directed graph is given as an adjacency list graph where graph[i] is the list of nodes reachable from i in one step (0 <= i < n). A node is a terminal if it has no outgoing edges. A node is safe if every possible walk starting from it eventually stops at a terminal (it can never get stuck in a cycle).

Return the sorted list of all safe nodes.

Examples

Input:  graph = [[1, 2], [2, 3], [5], [0], [5], [], []]
Output: [2, 4, 5, 6]
Explanation: 0, 1 and 3 form a cycle (0 -> 1 -> 3 -> 0); the others always end at 5 or 6.

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

Constraints

  • 1 <= n <= 10**4, total edges <= 3 * 10**4
  • Target: O(V + E) time.

Goals

  • Reverse the edges so that out-degree peeling becomes in-degree peeling
  • Classify each node by whether every walk from it must terminate
Starting Python…