585. Find the Town Judge
A town has n residents labeled 1 through n. Rumor says one resident may quietly hold the judge role, and that person is easy to characterize:
- the judge trusts nobody, and
- every other resident trusts the judge.
You are given n and an array trust of pairs, where trust[i] = [a, b] means resident a trusts resident b. Trust is one-directional and no pair appears twice.
Report which resident is the judge if exactly such a person exists, and -1 otherwise. (At most one resident can satisfy both conditions, so the answer is always well defined.)
Example 1:
Input: n = 2, trust = [[1,2]]
Output: 2
Explanation: Resident 1 trusts resident 2, and 2 trusts nobody. Everyone other than 2 (just resident 1) trusts 2, so 2 is the judge.
Example 2:
Input: n = 3, trust = [[1,3],[2,3]]
Output: 3
Explanation: Residents 1 and 2 both trust 3, and 3 appears in no pair as a truster. That is exactly the judge profile.
Example 3:
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Explanation: Resident 3 is trusted by everyone else, but 3 also trusts resident 1 — a judge trusts nobody, so there is no judge.
Constraints:
- 1 ≤ n ≤ 1000
- 0 ≤ trust.length ≤ 10⁴
- trust[i] = [a, b] with 1 ≤ a, b ≤ n and a ≠ b.
- All trust pairs are distinct.
Hints:
Think of trust as a directed graph: an edge a → b means a trusts b. Restate the judge in graph terms — what must the judge's outgoing and incoming edge counts be?
You do not need two separate counters. Give every resident one score: +1 each time someone trusts them, −1 each time they trust someone. The judge is the unique resident whose score reaches n − 1; anyone who trusts even once can never get there.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: n = 2, trust = [[1,2]]
Expected output: 2