997. Find the Town Judge
Problem
In a town of people 1…n, the judge (if any) trusts nobody and is trusted by everyone else, and at most one person fits. trust[i] = [a, b] means a trusts b. Return the judge's label, or −1.
Example: n = 3, trust = [[1,3],[2,3]] → 3; n = 3, trust = [[1,3],[2,3],[3,1]] → -1
The judge is trusted by everyone else (in-degree n − 1) and trusts nobody (out-degree 0). One score per person, in − out, equals n − 1 only for the judge.
Complexity: O(n + |trust|).
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
score = [0] * (n + 1)
for a, b in trust:
score[a] -= 1
score[b] += 1
return next((p for p in range(1, n + 1) if score[p] == n - 1), -1)
assert Solution().findJudge(2, [[1, 2]]) == 2
assert Solution().findJudge(3, [[1, 3], [2, 3]]) == 3
assert Solution().findJudge(3, [[1, 3], [2, 3], [3, 1]]) == -1
assert Solution().findJudge(1, []) == 1
class Solution {
public int findJudge(int n, int[][] trust) {
int[] score = new int[n + 1];
for (int[] t : trust) { score[t[0]]--; score[t[1]]++; }
for (int p = 1; p <= n; p++) if (score[p] == n - 1) return p;
return -1;
}
}
func findJudge(n int, trust [][]int) int {
score := make([]int, n+1) // trusted-by count minus trusts count
for _, t := range trust {
score[t[0]]--
score[t[1]]++
}
for p := 1; p <= n; p++ {
if score[p] == n-1 {
return p
}
}
return -1
}