MediumGraph

Minimum Number of Vertices to Reach All Nodes

LeetCode
1 approach, code in all languages

You are given a directed acyclic graph with n nodes labeled from 0 to n - 1, described by a list of directed edges where each edge [a, b] points from node a to node b. Starting from a chosen set of nodes and only walking along the direction of the edges, you want to be able to reach every node in the graph.

Return the smallest possible set of nodes from which all nodes are reachable. It is guaranteed that a unique solution exists.

You may return the nodes of the answer in any order.

Example 1

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

Output: [0,3]

From 0 you reach 1, 2, and 5; from 3 you reach 4 and then 2 and 5. Nodes 0 and 3 have no incoming edges, so they cannot be reached from anywhere else and must be included.

Example 2

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

Output: [0,2,3]

Nodes 0, 2, and 3 have indegree zero, so they must be starting points. From them nodes 1 and 4 are reachable, covering the entire graph.

Constraints

  • 2 <= n <= 10^5
  • 1 <= edges.length <= min(10^5, n * (n - 1) / 2)
  • edges[i].length == 2
  • 0 <= a, b < n
  • a != b, and all edge pairs are unique
  • The graph is a directed acyclic graph (DAG)
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now