Minimum starting vertices to reach a cyclic directed graph
I was asked this
No reports yet. Sign in to say where you were asked it.
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^50 <= len(edges) <= 2 * 10^50 <= 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.
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.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
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.
Sign in to submit your code; every attempt is kept here.
