Sponsored
Sponsored
The idea is to calculate the in-degree and out-degree for each person. A person is the town judge if their in-degree is n-1 (trusted by all other n-1 people) and their out-degree is 0 (trusting no one).
Time Complexity: O(trust.length), where trust.length is the total number of trust relationships.
Space Complexity: O(n), where n is the number of people in the town.
1class Solution {
2 public int findJudge(int n, int[][] trust) {
3 int[] inDegrees = new int[n + 1];
4 int[] outDegrees = new int[n + 1];
5
6 for (int[] t : trust) {
7 int a = t[0], b = t[1];
8 outDegrees[a]++;
9 inDegrees[b]++;
10 }
11
12 for (int i = 1; i <= n; i++) {
13 if (inDegrees[i] == n - 1 && outDegrees[i] == 0) {
14 return i;
15 }
16 }
17 return -1;
18 }
19}
20
The Java solution utilizes arrays to keep track of trust relationships. By computing the in-degree and out-degree for each person, the algorithm efficiently determines who, if anyone, is the town judge.
Java solution making use of a net trust array. The judge should have a net trust value of n-1 since they trust no one but everyone else trusts them.