LeetCode Solutions

997. Find the Town Judge

Time: $O(|\texttt{trust}| + n)$

Space: $O(n)$

			

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;
  }
};
			

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;
  }
}
			

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