Python coding

Starting steps that reach everything

A workflow has n steps numbered 0 to n - 1. Each pair [a, b] in triggers means that when step a runs, it sets off step b. The triggers never form a cycle. You launch some steps by hand, and every step they set off, directly or down a chain, runs too. Return, in increasing order, the smallest set of steps to launch so that every step runs.

Pairs may repeat, and triggers may be empty.

Besides the tests, one large input (3,000 steps, 6,000 triggers) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • starting_steps(6, [[0,1],[0,2],[2,5],[3,4],[4,2]]) → [0,3]
  • starting_steps(5, [[0,1],[2,1],[3,1],[1,4],[2,4]]) → [0,2,3]
  • starting_steps(3, []) → [0,1,2]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A step that some trigger points at will run anyway if you launch whatever fires it. Which steps can nothing set off?

Hint 2

Those are the in-degree-0 steps, the ones Kahn's algorithm queues first. With no cycle, walking any step's triggers backwards always ends at one of them.

Solution and why it works
pythonO(n + E), E = len(triggers) · O(n)
def starting_steps(n: int, triggers: list[list[int]]) -> list[int]:
    fired = [False] * n                  # fired[s]: some trigger points at s (in-degree > 0)
    for _, b in triggers:
        fired[b] = True
    return [s for s in range(n) if not fired[s]]

A step with an incoming trigger never needs launching: follow its triggers backwards and, because there is no cycle, the walk must stop at a step nothing fires. So the in-degree-0 steps reach everything, and each of them must be launched, since nothing else sets it off. That is exactly where Kahn's algorithm starts. The trap is simulating: launching each step and running a BFS to see what it covers is O(n·(n + E)).