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.
1public class 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 foreach (var t in 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 C# implementation uses arrays to store the in-degree and out-degree of every person based on the trust relationships. It then iterates to find the potential town judge based on the required properties.
JavaScript solution with a netTrust array identifying the judge by finding the person with net trust equal to n-1.