Skip to content

997. Find the Town Judge 👍

  • Time: $O(n + |\texttt{trust}|)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int findJudge(int n, vector<vector<int>>& trust) {
    vector<int> count(n + 1);

    for (vector<int>& t : trust) {
      --count[t[0]];
      ++count[t[1]];
    }

    for (int i = 1; i < n + 1; ++i)
      if (count[i] == n - 1)
        return i;

    return -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int findJudge(int n, int[][] trust) {
    int[] count = new int[n + 1];

    for (int[] t : trust) {
      --count[t[0]];
      ++count[t[1]];
    }

    for (int i = 1; i < n + 1; ++i)
      if (count[i] == n - 1)
        return i;

    return -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def findJudge(self, n: int, trust: list[list[int]]) -> int:
    count = [0] * (n + 1)

    for a, b in trust:
      count[a] -= 1
      count[b] += 1

    for i in range(1, n + 1):
      if count[i] == n - 1:
        return i

    return -1