Skip to content

2924. Find Champion II 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int findChampion(int n, vector<vector<int>>& edges) {
    int ans = -1;
    int count = 0;
    vector<int> inDegrees(n);

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

    for (int i = 0; i < n; ++i)
      if (inDegrees[i] == 0) {
        ++count;
        ans = i;
      }

    return count > 1 ? -1 : ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int findChampion(int n, int[][] edges) {
    int ans = -1;
    int count = 0;
    int[] inDegrees = new int[n];

    for (int[] edge : edges) {
      final int v = edge[1];
      ++inDegrees[v];
    }

    for (int i = 0; i < n; ++i)
      if (inDegrees[i] == 0) {
        ++count;
        ans = i;
      }

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

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

    return (-1 if inDegrees.count(0) > 1
            else inDegrees.index(0))