Minimum Number of Vertices to Reach All Nodes

MediumGraphshashing

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 needed

Problem

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

Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
Output: [0,3]
From 0 you reach 1, 2, 5; from 3 you reach 4, 2, 5. Neither 0 nor 3 can be reached from anywhere else.
Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
Output: [0,2,3]
Vertices 0, 2, and 3 have no incoming edges, so each must be a start.

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.

More hashing problems