🎉 One-stop destination for all your technical interview Preparation 🎉
In a town, there are 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:
You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
trusts count == 0
and trusted count == n-1
(everyone except town judge), then it is the town judge.else we return -1.class Solution {
public:
int findJudge(int n, vector<vector<int>>& t)
{
vector<int> trusts(n + 1, 0), trusted(n + 1, 0);
for (int i = 0; i < t.size(); i++) { // here t.size() not n
trusts[t[i][0]]++;
trusted[t[i][1]]++;
}
for (int i = 1; i <= n; i++) {
if (trusted[i] == n - 1 && trusts[i] == 0) {
return i;
}
}
return -1;
}
};