Minimum Number of Vertices to Reach all Nodes

Medium Topics Company Tags

You are given a directed acyclic graph with n nodes labeled 0 through n - 1. Each pair [from, to] in edges represents a directed edge from from to to.

Return a smallest set of starting nodes from which every node can be reached by following directed edges. A starting node is considered reachable from itself.

The smallest set is unique. Return its node labels in any order; do not include duplicates.

Example 1:

Minimum Number of Vertices to Reach All Nodes, example 1: illustration of the example

Input: n = 5
edges = [[0,1],[2,1],[1,3]]

Output: [0,2,4]

Explanation: Start from 0, 2, and the isolated node 4. Nodes 1 and 3 are reachable from 0 or 2. None of 0, 2, or 4 can be reached from another node, so all three are necessary.

Example 2:

Minimum Number of Vertices to Reach All Nodes, example 2: illustration of the example

Input: n = 4
edges = [[3,2],[2,1],[1,0]]

Output: [3]

Explanation: Starting from node 3 reaches the chain 3 → 2 → 1 → 0, covering every node with one starting point.

Example 3:

Minimum Number of Vertices to Reach All Nodes, example 3: illustration of the example

Input: n = 5
edges = [[0,4],[1,4],[2,4],[3,4]]

Output: [0,1,2,3]

Explanation: Nodes 0, 1, 2, and 3 cannot be reached from any other node, so each must be chosen. Node 4 is then reachable from any of them.

Constraints:

  • 2 <= n <= 100000
  • 1 <= edges.length <= min(100000, n * (n - 1) / 2)
  • edges[i].length == 2
  • Both endpoints are node labels between 0 and n - 1.
  • All directed edges are distinct.
  • The graph has no directed cycles.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.