Minimum Number of Vertices to Reach All Nodes
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
You are given a directed acyclic graph with n vertices labeled 0 to n - 1 and a list of directed edges, where [from, to] is an edge from from to to. There are no duplicate edges.
Find the smallest set of starting vertices such that every vertex in the graph is reachable from at least one of them (a vertex reaches itself). This set is unique.
Return its vertices sorted in **ascending** order. Aim for O(n + e) time.
Examples
Constraints
- 2 <= n <= 10^5
- 1 <= edges.length <= min(10^5, n * (n - 1) / 2)
- edges[i].length == 2
- 0 <= from, to < n
- All edges are distinct and the graph is acyclic
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.