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:
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.
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
1 <= n <= 1000
0 <= trust.length <= 104
trust[i].length == 2
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
# make directional graph
trusts={x: [] for x in range(1,n+1)}
for p1,p2 in trust:
trusts[p1].append(p2)
town_judge=[x for x in trusts if not trusts[x]]
# check if there is town_judge
# if there is no town_judge, or more than one town_judge
if len(town_judge)==0 or len(town_judge)>1:
return -1
# if everybody trusts town judge
return town_judge[0] if sum(list(trusts.values()),[]).count(town_judge[0])==len(trusts)-1 else -1
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
trusts = [0] * (N+1)
for (a, b) in trust:
trusts[a] -= 1
trusts[b] += 1
for i in range(1, len(trusts)):
if trusts[i] == N-1:
return i
return -1
Given constraints are
1. The judge believes no one.
2. Everybody believes judge.
👉 So, from these two points, we can say that if any person is trusted byN - 1
persons and the same person believes no one*, then we can say that he is a judge.
trusts[a] -= 1
?Because if we only consider trusts[b] += 1
, then even if that person believes anyone in that village, it returns him as judge if he is trusted by N-1
persons.
References