Leetcode 997. Find the Town Judge
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] = [a, b]
represents that the person labeled a
trusts the person labeled b
.
Return the label of the town judge if the town judge exists and can be identified, or return -1
otherwise.
inDegree
and outDegree
to count the number of trusts each person receives and gives respectively.trust
array and for each trust[i] = [a, b]
, increment outDegree[a]
and inDegree[b]
.inDegree
and outDegree
, check if there’s a person j
such that:
inDegree[j] == n - 1
(everyone trusts this person, except themselves).outDegree[j] == 0
(this person trusts no one).-1
.n
is the number of people and t
is the length of the trust array.#include <vector>
using namespace std;
class Solution {
public:
int findJudge(int n, vector<vector<int>>& trust) {
if (n == 1) {
return 1; // If there's only one person, they are trivially the judge.
}
vector<int> inDegree(n + 1, 0);
vector<int> outDegree(n + 1, 0);
// Populate in and out degrees
for (const auto& t : trust) {
int a = t[0];
int b = t[1];
outDegree[a]++;
inDegree[b]++;
}
// Find the judge
for (int i = 1; i <= n; ++i) {
if (inDegree[i] == n - 1 && outDegree[i] == 0) {
return i; // This person satisfies the conditions of the judge
}
}
// No judge found
return -1;
}
};
n
is always at least 1?
n
is at least 1.trust
always be within the bounds mentioned?
With these considerations and strategy, the provided solution efficiently identifies the town judge if they exist.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?