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 person a trusts person b.
Return the label of the town judge if the town judge exists and can be identified. Otherwise, return -1.
Input: n = 2, trust = [[1,2]]
Output: 2
Input: n = 3, trust = [[1,3],[2,3]]
Output: 3
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
trust array is empty and n > 1?
trust is empty and n > 1, it means that no one trusts anyone. Hence, there can’t be a judge, as the judge needs at least n-1 people to trust them.n == 1?
n == 1, the single person is trivially the judge as there is no one else in the town.We can use a degree counting approach to solve this problem:
trusts and trusted_by of size n+1 to count how many people each person trusts and how many people trust each person, respectively.trust array and populate these arrays.i with trusts[i] == 0 and trusted_by[i] == n-1.def findJudge(n, trust):
if n == 1:
return 1
trusts = [0] * (n + 1)
trusted_by = [0] * (n + 1)
for a, b in trust:
trusts[a] += 1
trusted_by[b] += 1
for i in range(1, n + 1):
if trusts[i] == 0 and trusted_by[i] == n - 1:
return i
return -1
trusts and trusted_by arrays takes O(n) time as we iterate over the trust array once.This solution is efficient and should handle the input constraints well. If you have any specific edge cases or further questions, feel free to ask!
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?