call(back)
Algorithms & Data StructuresmediumSign in to star problems

Sensor Network III

Field sensors numbered 0 to n − 1 are linked by directed edges (u, v): data flows from u to v, so u must be processed before v. Return an order in which all the sensors can be processed, or an empty list when a cycle makes that impossible. Any valid order is accepted.

n = 4, edges = [[0, 1], [0, 2], [1, 3], [2, 3]]   ->  [0, 1, 2, 3]  (or [0, 2, 1, 3])
n = 2, edges = [[0, 1], [1, 0]]                   ->  []

Hints

Hint 1

Count each sensor's incoming edges. A sensor with none can be processed now; processing it removes its outgoing edges.

Hint 2

If you run out of sensors with no remaining inputs before placing all n, the rest sit on or behind a cycle.

Asked at