Find The Town Judge Problem
Description
LeetCode Problem 997.
In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
- The town judge trusts nobody.
- Everybody (except for the town judge) trusts the town judge.
- There is exactly one person that satisfies properties 1 and 2.
You are given an array trust where trust[i] = [a_i, b_i] representing that the person labeled a_i trusts the person labeled b_i.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
Example 1:
Input: n = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: n = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: n = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: n = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
Constraints:
- 1 <= n <= 1000
- 0 <= trust.length <= 10^4
- trust[i].length == 2
- All the pairs of trust are unique.
- a_i != b_i
- 1 <= a_i, b_i <= n
Solution
Approach: Trust Score (In-Degree Minus Out-Degree)
Think of the trust pairs as a directed graph: a -> b means a trusts b. The judge is the person with in-degree n - 1 (everyone else trusts them) and out-degree 0 (they trust nobody).
Both conditions fit in one number per person: score[p] = (number of people who trust p) - (number of people p trusts).
- For every pair
[a, b], doscore[a] -= 1andscore[b] += 1. - Return the person whose score is exactly
n - 1, or-1if there is none.
Why does score == n - 1 mean both conditions? A person can be trusted by at most n - 1 others, since nobody trusts themselves and the pairs are unique. So a score of n - 1 needs the full n - 1 incoming trusts and no outgoing trust at all. At most one person can reach it, because then all others trust somebody and their scores are below n - 1.
Don't forget n = 1 with no pairs: the only person trusts nobody and is trusted by all 0 others, so the answer is 1. The score check gives this for free, since score[1] = 0 = n - 1.
Complexity: O(n + t) time, where t is the length of trust, and O(n) space for the scores.
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
# score[p] = (people who trust p) - (people p trusts)
score = [0] * (n + 1)
for a, b in trust:
score[a] -= 1
score[b] += 1
for person in range(1, n + 1):
if score[person] == n - 1: # trusted by all n - 1 others and trusts nobody
return person
return -1
Now write it from memory
Close the write-up and solve it yourself against the tests.