Leetcode 1557: Minimum Number of Vertices to Reach All Nodes

grid47
grid47
Exploring patterns and algorithms
Jun 4, 2024 5 min read

In a directed acyclic graph with n vertices, find the smallest set of vertices from which all nodes in the graph are reachable.
Problem
Approach
Steps
Complexity
Input: The input consists of the number of vertices n and an array of directed edges.
Example: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
Constraints:
• 2 <= n <= 10^5
• 1 <= edges.length <= min(10^5, n * (n - 1) / 2)
• edges[i].length == 2
• 0 <= fromi, toi < n
• All pairs (fromi, toi) are distinct
Output: Return the smallest set of vertices from which all nodes in the graph are reachable.
Example: Output: [0, 2, 3]
Constraints:
• The output should be a list of vertices.
Goal: The goal is to find the smallest set of vertices that can reach all the nodes in the graph.
Steps:
• 1. Initialize an array to track the number of incoming edges for each vertex.
• 2. Traverse the edges to update the number of incoming edges for each vertex.
• 3. Identify vertices that have no incoming edges (i.e., vertices that must be included in the set).
• 4. Return the list of these vertices.
Goal: The solution should work efficiently for large graphs with up to 10^5 vertices and 10^5 edges.
Steps:
• The solution must handle up to 10^5 vertices and edges efficiently.
Assumptions:
• The graph is a directed acyclic graph (DAG).
• There is always a unique solution.
Input: n = 6, edges = [[0, 1], [0, 2], [2, 5], [3, 4], [4, 2]]
Explanation: From vertex 0, we can reach nodes [0, 1, 2, 5], and from vertex 3, we can reach nodes [3, 4, 2, 5]. Therefore, the smallest set of vertices is [0, 3].

Input: n = 5, edges = [[0, 1], [2, 1], [3, 1], [1, 4], [2, 4]]
Explanation: The vertices 0, 2, and 3 are not reachable from any other node, so they must be included in the set. Any of these vertices can reach nodes 1 and 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus