Give each person one score for incoming trust and minus one for outgoing trust; the judge's final score is n minus one.
Complexity
O(n + t) time and O(n) space.
Find the person trusted by everyone else who trusts nobody.
Give each person one score for incoming trust and minus one for outgoing trust; the judge's final score is n minus one.
O(n + t) time and O(n) space.
package main
func findJudge(n int, trust [][]int) int {
score := make([]int, n+1)
for _, relation := range trust {
score[relation[0]]--
score[relation[1]]++
}
for person := 1; person <= n; person++ {
if score[person] == n-1 {
return person
}
}
return -1
}
class Solution:
def findJudge(self, n: int, trust: list[list[int]]) -> int:
score = [0] * (n + 1)
for source, target in trust: score[source] -= 1; score[target] += 1
return next((person for person in range(1, n + 1) if score[person] == n - 1), -1)
function findJudge(n: number, trust: number[][]): number {
const score = new Array<number>(n + 1).fill(0);
for (const [from, to] of trust) { score[from] -= 1; score[to] += 1; }
for (let person = 1; person <= n; person += 1) if (score[person] === n - 1) return person;
return -1;
}