Find the Town Judge - Problem
In a small town with n people (labeled from 1 to n), there's a rumor about a secret town judge. This mysterious figure has two unique characteristics:
- ๐ซ The judge trusts nobody - they have zero outgoing trust relationships
- ๐ฅ Everyone trusts the judge - all other (n-1) people trust the judge
You're given a trust array where trust[i] = [a, b] means person a trusts person b. If a trust relationship isn't in the array, it doesn't exist.
Goal: Find and return the label of the town judge. If no such person exists or cannot be uniquely identified, return -1.
Example: With 3 people and trust relationships [[1,3],[2,3]], person 3 is the judge because everyone trusts them (1โ3, 2โ3) and they trust nobody.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 2, trust = [[1,2]]
โบ
Output:
2
๐ก Note:
Person 1 trusts person 2, and person 2 trusts nobody. Since there are only 2 people, person 2 is trusted by everyone else (just person 1) and trusts nobody, making them the judge.
example_2.py โ Three People
$
Input:
n = 3, trust = [[1,3],[2,3]]
โบ
Output:
3
๐ก Note:
Person 3 is trusted by both person 1 and person 2, totaling n-1=2 people. Person 3 doesn't trust anyone. Therefore, person 3 is the town judge.
example_3.py โ No Judge
$
Input:
n = 3, trust = [[1,3],[2,3],[3,1]]
โบ
Output:
-1
๐ก Note:
Person 3 is trusted by persons 1 and 2, but person 3 also trusts person 1. Since the judge cannot trust anyone, there is no town judge.
Constraints
- 1 โค n โค 1000
- 0 โค trust.length โค 104
- trust[i].length == 2
- All pairs trust[i] are unique
- trust[i][0] โ trust[i][1]
Visualization
Tap to expand
Understanding the Visualization
1
Map Relationships
Visualize trust as arrows: person A โ person B means A trusts B
2
Count Connections
Judge has n-1 incoming arrows (trusted by all) and 0 outgoing arrows (trusts none)
3
Apply Score System
Use +1 for incoming trust, -1 for outgoing trust. Judge scores exactly n-1
Key Takeaway
๐ฏ Key Insight: The judge is like a celebrity in the trust network - everyone follows them, but they follow nobody back. Use the scoring system (+1 trusted, -1 trusts) to find them efficiently in one pass!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code