Find the Town Judge
The key idea
The judge is trusted by everyone else and trusts nobody. Give each person
+1 when someone trusts them and -1 when they trust someone. The judge is the one and only person whose net score equals n - 1.Problem
In a town of 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:
1. The town judge trusts nobody.
2. Everybody (except the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties 1 and 2.
You are given an array trust where trust[i] = [a, b] means that the person labeled a trusts the person labeled b. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
Constraints
1 <= n <= 10000 <= trust.length <= 10^4trust[i].length == 2- All the pairs of
trustare unique. trust[i][0] != trust[i][1]1 <= trust[i][0], trust[i][1] <= n
Examples
Input: n = 2, trust = [[1,2]]
Output: 2
Input: n = 3, trust = [[1,3],[2,3]]
Output: 3
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Complexity
Time: O(n + e) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Graph problems
- Cheapest Flights Within K StopsMEDIUM
- Clone GraphMEDIUM
- Course Schedule IVMEDIUM
- Evaluate DivisionMEDIUM
- Min Cost to Connect All PointsMEDIUM
- Minimum Height TreesMEDIUM
- Network Delay TimeMEDIUM
- Number of ProvincesMEDIUM
- Path With Minimum EffortMEDIUM
- Reconstruct ItineraryHARD
- Swim in Rising WaterHARD