IT/Computer Science
[Leetcode/Graph (In-Degree/Out-Degree)] 997. Find the Town Judge
Diana Kang
2025. 6. 2. 22:32
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
# If there's only one person and no trust relationships, that person is the judge
if n == 1 and not trust:
return 1
# Initialize trust counts
trust_scores = [0] * (n+1)
for a,b in trust:
trust_scores[a] -= 1 # a trusts someone → cannot be the judge
trust_scores[b] += 1 # b is trusted → potential to be the judge
# The judge should be trusted by n - 1 people and trust no one
for i in range(1, n+1):
if trust_scores[i] == n-1:
return i
return -1