Skip to content

1557. Minimum Number of Vertices to Reach All Nodes 👍

  • Time: $O(|E|)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
    vector<int> ans;
    vector<int> inDegrees(n);

    for (const vector<int>& edge : edges)
      ++inDegrees[edge[1]];

    for (int i = 0; i < inDegrees.size(); ++i)
      if (inDegrees[i] == 0)
        ans.push_back(i);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public List<Integer> findSmallestSetOfVertices(int n, List<List<Integer>> edges) {
    List<Integer> ans = new ArrayList<>();
    int[] inDegrees = new int[n];

    for (List<Integer> edge : edges)
      ++inDegrees[edge.get(1)];

    for (int i = 0; i < inDegrees.length; ++i)
      if (inDegrees[i] == 0)
        ans.add(i);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def findSmallestSetOfVertices(
      self,
      n: int,
      edges: list[list[int]],
  ) -> list[int]:
    inDegrees = [0] * n

    for _, v in edges:
      inDegrees[v] += 1

    return [i for i, d in enumerate(inDegrees) if d == 0]