Minimum starting vertices to reach a cyclic directed graph

0
Sign in

You are given a directed graph with n vertices labeled 0 to n - 1 and a list edges, where edges[i] = [u, v] is a directed edge from u to v. The graph may contain cycles, self-loops and duplicate edges.

Choose the smallest set of starting vertices such that every vertex in the graph can be reached from at least one of them (a starting vertex reaches itself).

Implement:

def min_start_vertices(n: int, edges: list[list[int]]) -> list[int]: ...

If several minimum sets exist, return the one that uses the smallest vertex id from each group of interchangeable choices, sorted in ascending order.

Constraints

  • 0 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= u, v < n

Example 1

n = 5, edges = [[0, 1], [1, 2], [2, 0], [3, 2]]

Output: [3, 4]. Vertex 3 reaches the cycle 0 -> 1 -> 2 -> 0. Vertex 4 has no edges, so it must be chosen itself.

Example 2

n = 4, edges = [[0, 1], [1, 0], [1, 2], [2, 3], [3, 2]]

Output: [0]. Every vertex has an incoming edge, but starting at 0 reaches 1, then 2 and 3.

Note: if the graph had no cycles, the answer would simply be the vertices with no incoming edges. Your solution must handle cycles.

AirbnbCodingHard

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.