Skip to content
BytePatterns

Nodes Clear of Cycles

MediumGraphs#dfs#graph-colouring#cycle-detection~30m

Problem

A build system has n steps numbered 0 to n - 1, and graph[i] lists the steps that step i hands off to, as a directed graph. A step is safe when every chain of hand-offs starting from it eventually stops, which means no chain from it can reach a cycle. Return the safe steps in increasing order. A step that hands off to itself forms a cycle.

Examples

Input:  graph = [[1, 2], [2], [3], [], [5], [4], [3, 4]]
Output: [0, 1, 2, 3]
Why:    4 and 5 hand off to each other forever, and 6 can reach them
Input:  graph = [[], [0], [1]]
Output: [0, 1, 2]
Why:    every chain ends at step 0, which hands off to nobody
Input:  graph = [[0]]
Output: []
Why:    edge case, the only step loops back to itself

Hints

0 / 3

Stuck on the idea rather than the code? Cycles in a Directed Graph covers it.