← Questions

Minimum starting vertices to reach a cyclic directed graph

0
AirbnbCoding

A coding interview question asked at Airbnb. It tests graphs, strongly connected components and dfs.

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.

Clarifying questions

  • Is a vertex whose only incoming edge is a self-loop a required start?
  • Does "the smallest vertex id from each group" mean the smallest id in each strongly connected component that must hold a start?
  • Should n = 0 return []?
  • Is recursion depth a concern, given chains of up to 10^5 vertices?

What a strong answer covers

  • Finds the strongly connected components (Tarjan or Kosaraju) and builds the condensation, which is a DAG.
  • A component with no incoming edge from another component must contain a start, and one start in each such component reaches everything: the answer is the smallest vertex of each source component, sorted.
  • Runs in O(n + e), ignores self-loops and duplicate edges when computing in-degrees between components, and uses an iterative DFS to avoid stack overflow.
  • Explains why taking vertices with in-degree 0 fails on cycles (example 2).
  • Tests isolated vertices, one big cycle, two cycles joined by one edge, and an empty graph.

Follow-ups

  • Return only the number of starts, or the source components themselves.
  • Edges are added over time: keep the answer current after each addition.
  • Find the fewest edges to add so one vertex reaches everything.

Where it's asked

What it tests

graphs · strongly connected components · dfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding