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]
representing 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.
Question: What should be returned if there are no people in the town (n = 0)?
Answer: Return -1
since it’s not possible to have a town judge without any people.
Question: Can there be multiple trust relationships for the same person in the trust
list?
Answer: Yes, a person can trust multiple other people but in the context of the town judge problem, it does not affect the criterion where a town judge trusts nobody.
Question: Is it possible for the trust
array to be empty?
Answer: Yes, if trust
is empty and n
is 1, the single individual is by definition the town judge.
0
).n-1
people.public class FindTownJudge {
public int findJudge(int n, int[][] trust) {
if (n == 0) return -1;
if (trust.length == 0 && n == 1) return 1;
int[] trustCount = new int[n + 1];
int[] trustedByCount = new int[n + 1];
for (int[] t : trust) {
trustCount[t[0]]++;
trustedByCount[t[1]]++;
}
for (int i = 1; i <= n; i++) {
if (trustCount[i] == 0 && trustedByCount[i] == n - 1) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
FindTownJudge solution = new FindTownJudge();
int[][] trust = { {1, 2}, {2, 3}, {3, 1} };
int result = solution.findJudge(3, trust);
System.out.println(result); // Outputs: -1
}
}
Time Complexity: The solution iterates through the trust
array once (O(m)), where m
is the number of trust relationships. Then, it iterates through the list of people once (O(n)). Therefore, the overall time complexity is O(m + n).
Space Complexity: The space complexity is O(n) for the arrays that are used to count the trust relationships.
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?