Advertisement

Minimum Number of Vertices to Reach All Nodes - LeetCode 1557 Solution

Minimum Number of Vertices to Reach All Nodes - Complete Solution Guide

Minimum Number of Vertices to Reach All Nodes is LeetCode problem 1557, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given a directed acyclic graph , with n vertices numbered from 0 to n-1 , and an array edges where edges[i] = [from i , to i ] represents a directed edge from node from i to node to i . Find the smallest set of vertices from which all nodes in the graph are reachable . It's guaranteed that a unique solution exists. Notice that you can 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] Explanation: It's not possible to reach all the no

Detailed Explanation

The problem asks us to find the smallest set of vertices in a directed acyclic graph (DAG) such that all nodes in the graph are reachable from this set. A crucial detail is that the solution is guaranteed to be unique. Essentially, we need to find the nodes that have no incoming edges, as these nodes must be included in the minimal set to reach all other nodes.

Solution Approach

The solution iterates through the edges and marks all nodes that have incoming edges. Then, it iterates through all nodes and adds any node that wasn't marked (i.e., has no incoming edges) to the result list. This works because any node with an incoming edge is reachable from another node, so we only need the nodes that have no incoming edges to start from.

Step-by-Step Algorithm

  1. Step 1: Initialize a boolean array `has_incoming_edge` of size `n` to `false`. This array will track which nodes have incoming edges.
  2. Step 2: Iterate through the `edges` array. For each edge `[from, to]`, set `has_incoming_edge[to]` to `true`.
  3. Step 3: Initialize an empty list `result` to store the vertices in the smallest set.
  4. Step 4: Iterate through all nodes from `0` to `n-1`. For each node `i`, if `has_incoming_edge[i]` is `false`, add `i` to the `result` list.
  5. Step 5: Return the `result` list.

Key Insights

  • Insight 1: Nodes with no incoming edges are the key. Any node with an incoming edge can be reached from another node, so the starting set only needs nodes without incoming edges.
  • Insight 2: Since it's a DAG and a unique solution exists, the nodes without incoming edges will be sufficient to reach every other node in the graph.
  • Insight 3: No need to perform graph traversals (BFS/DFS). We can determine the result by simply checking which nodes have incoming edges.

Complexity Analysis

Time Complexity: O(n + e)

Space Complexity: O(n)

Topics

This problem involves: Graph.

Companies

Asked at: Airbnb.