Identify the person who is trusted by everyone else but trusts nobody.
Problem
In a town with n people labeled from 1 to n, some pairs describe trust relationships. Each pair [a, b] means that person a trusts person b.
A town judge is a person who satisfies both conditions:
- The judge trusts nobody.
- Everyone else in the town trusts the judge.
Return the label of the judge if one exists. Otherwise, return -1.
Clarification
- There may be no judge.
- A person can appear in the trust list multiple times in the input only if the platform data allows it; the standard interpretation is a list of directed trust edges.
- The answer is unique if a judge exists.
Input Format
n: integer, the number of people labeled1..ntrust: list of pairs[a, b]representing thatatrustsb
Output Format
- Return a single integer: the label of the town judge, or
-1if no such person exists.
Constraints
1 <= ntrust.lengthmay be0- Each trust pair contains two distinct labels in the range
1..n
Example 1
Input
n = 2 trust = [[1,2]]
Output
2
Explanation
Person 2 is trusted by person 1 and trusts nobody, so person 2 is the judge.
Example 2
Input
n = 3 trust = [[1,3],[2,3]]
Output
3
Explanation
Person 3 is trusted by everyone else and trusts no one.
Show 1 more example
Example 3
Input
n = 3 trust = [[1,3],[2,3],[3,1]]
Output
-1
Explanation
Person 3 trusts person 1, so person 3 cannot be the judge.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.