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 Single Array Trust Score Approach INPUT n = 3 people in town 1 2 Judge? 3 trusts trusts n = 3 trust = [[1,2],[3,2]] [a,b] means a trusts b ALGORITHM STEPS 1 Initialize trust score score[n+1] array = all 0s 2 Process trust pairs score[a]-- , score[b]++ 3 Find person with score = n-1 4 Return judge or -1 if no one found Trust Score Calculation Person: 1 2 3 Initial: 0 0 0 [1,2]: -1 +1 0 [3,2]: -1 +2 -1 FINAL RESULT 2 JUDGE Trust Score score[2] = 2 n - 1 = 3 - 1 = 2 OK - MATCH! Output: 2 Key Insight: Use a single trust score array: decrement when someone trusts (they can't be judge), increment when trusted. The judge has score = n-1 (trusted by all n-1 others, trusts nobody). Time: O(n + trust.length) | Space: O(n) TutorialsPoint - Find the Town Judge | Single Array Trust Score Approach
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