Find the Town Judge - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, trust = [[1,2],[3,2]]
Output: 2
💡 Note: Person 1 trusts person 2, person 3 trusts person 2, and person 2 trusts nobody. Person 2 is trusted by 2 people (everyone except themselves) and trusts nobody, so they are the judge.
Example 2 — No Judge
$ Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
💡 Note: No one satisfies the judge criteria. Person 3 is trusted by persons 1 and 2, but person 3 also trusts person 1, so they cannot be the judge.
Example 3 — Single Person
$ Input: n = 1, trust = []
Output: 1
💡 Note: With only one person in the town, they must be the judge by default since there are no trust relationships.

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ trust.length ≤ 104
  • trust[i].length == 2
  • All the pairs of trust are unique
  • ai ≠ bi
  • 1 ≤ ai, bi ≤ n

Visualization

Tap to expand
Find the Town Judge: Trust Relationship AnalysisInput: n=3, trust=[[1,2],[3,2]]123truststrustsTrusts: 1Trusted by: 0Trusts: 0Trusted by: 2Trusts: 1Trusted by: 0Judge Criteria: Trusts nobody AND Trusted by n-1 peoplePerson 2 is the Judge!
Understanding the Visualization
1
Input
n people and trust array showing who trusts whom
2
Process
Count trust relationships for each person
3
Output
Person trusted by n-1 others who trusts nobody
Key Takeaway
🎯 Key Insight: The judge has a unique trust signature - trusted by all others but trusts nobody
Asked in
Amazon 15 Google 8
156.0K Views
Medium Frequency
~15 min Avg. Time
3.2K 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