[Leetcode]997. Find the Town Judge

김지원·2022년 5월 19일
0

📄 Description

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:

  1. The town judge trusts nobody.
  2. Everybody (except for the town judge) trusts the town judge.
  3. There is exactly one person that satisfies properties 1 and 2.
    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.

Example 1:

Input: n = 2, trust = [[1,2]]
Output: 2

Example 2:

Input: n = 3, trust = [[1,3],[2,3]]
Output: 3

Example 3:

Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1

Constraints:

  • 1 <= n <= 1000
  • 0 <= trust.length <= 104
  • trust[i].length == 2
  • All the pairs of trust are unique.
  • ai!=bi{a_i} != {b_i}
  • 1<=ai,bi<=n1 <= {a_i}, {b_i} <= n

💻 My Submission

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

🎈 Better Solution

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

💡 How to solve the Problem

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 by N - 1 persons and the same person believes no one*, then we can say that he is a judge.

❓ Why 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

profile
Make your lives Extraordinary!

0개의 댓글