#1557

Minimum Number of Vertices to Reach All Nodes

Medium
Graph TheoryGraph TraversalCounting In-Degrees
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

The optimal solution leverages the property of directed acyclic graphs (DAGs) that nodes with no incoming edges are essential to reach other nodes. Thus, we can simply identify nodes with no incoming edges to find the minimum set of vertices.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array to count incoming edges for each vertex.
  2. 2Step 2: Traverse the edges and populate the incoming edge count for each vertex.
  3. 3Step 3: Collect all vertices with zero incoming edges into the result list.
solution.py8 lines
1# Full working Python code
2from collections import defaultdict
3
4def minVertices(n, edges):
5    in_degree = [0] * n
6    for u, v in edges:
7        in_degree[v] += 1
8    return [i for i in range(n) if in_degree[i] == 0]

Complexity note: The time complexity is linear with respect to the number of vertices (n) and edges (m) because we traverse each edge once to build the in-degree array.

  • 1Nodes with no incoming edges must be included in the result as they cannot be reached from any other node.
  • 2In a directed acyclic graph, the minimum set of vertices to reach all nodes corresponds to the sources of the graph.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.