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.
1def findJudge(n, trust):
2 in_degrees = [0] * (n + 1)
3 out_degrees = [0] * (n + 1)
4
5 for a, b in trust:
6 out_degrees[a] += 1
7 in_degrees[b] += 1
8
9 for i in range(1, n + 1):
10 if in_degrees[i] == n - 1 and out_degrees[i] == 0:
11 return i
12 return -1
13
This Python function counts the number of people each individual trusts and the number of people who trust them using two separate lists. It then searches for a person who is trusted by n-1 others while trusting no one.
An alternative approach is to use a single array to calculate the difference between in-degrees and out-degrees. For the judge, this difference should be n-1.
Time Complexity: O(trust.length)
Space Complexity: O(n)
1#include <vector>
2using namespace std;
int findJudge(int n, vector<vector<int>>& trust) {
vector<int> netTrust(n + 1, 0);
for (auto& t : trust) {
int a = t[0], b = t[1];
netTrust[a]--;
netTrust[b]++;
}
for (int i = 1; i <= n; i++) {
if (netTrust[i] == n - 1) {
return i;
}
}
return -1;
}
C++ solution using an array to calculate net trust for each person. If a person has a net trust value of n-1, they are the judge.