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
Trust Network: Finding the Judge12345Analysis Results:โ€ข Person 3: Trusted by 4 people (1,2,4,5) โœ“ Trusts nobody โœ“โ€ข Trust Score: +4 incoming, -0 outgoing = +4 = n-1 โœ“๐ŸŽฏ Person 3 is the Town Judge!
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!
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 5
89.5K Views
High Frequency
~12 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen