Minimum Number of Vertices to Reach All Nodes

Given a directed acyclic graph with n vertices numbered 0 to n - 1 and an array edges where edges[i] = [from_i, to_i] is a directed edge from from_i to to_i, find the smallest set of vertices from which every node in the graph is reachable. A unique solution is guaranteed. You may return the vertices in any order.

30:00

Minimum Number of Vertices to Reach All Nodes
medium
Free written solution
Topics
Companies

Given a directed acyclic graph with n vertices numbered 0 to n - 1 and an array edges where edges[i] = [from_i, to_i] is a directed edge from from_i to to_i, find the smallest set of vertices from which every node in the graph is reachable. A unique solution is guaranteed. You may return the vertices in any order.

Example 1:
Input: {"n":6,"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]]}
Output: [0,3]
Constraints:
  • 2≤n≤1052 \leq n \leq 10^5

  • 1≤edges.length≤min⁡(105,n(n−1)/2)1 \leq \text{edges.length} \leq \min(10^5, n(n - 1) / 2)

  • edges[i].length=2\text{edges}[i].\text{length} = 2

  • 0≤fromi,toi<n0 \leq \text{from}_i, \text{to}_i < n

  • All pairs (fromi,toi)(\text{from}_i, \text{to}_i) are distinct.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":6,"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]]}

Every vertex starts unmarked. A vertex that no edge points into can only be reached by starting there, so it must be in the answer.

012345

■ has an incoming edge

■ no incoming edge = must start here

edges read

0/5

marked

0/6

scanned

0/6

result (0)

[]

Variables
VariableValue
n6
edges5
v-
roots0
DepthFunction Call
Stack empty
0/13