Advertisement
DeepRest

Find the Town Judge

Jan 3rd, 2022 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. class Solution:
  2.     def findJudge(self, n: int, trust: List[List[int]]) -> int:
  3.         out = Counter(ele[0] for ele in trust)
  4.         inc = Counter(ele[1] for ele in trust)
  5.         for i in range(1, n+1):
  6.             if out[i] == 0 and inc[i] == n-1:
  7.                 return i
  8.         return -1
  9.  
  10. #using one hashtable
  11. '''
  12. """
  13. Why mp[i] == n-1 works?
  14. Our goal is to find a node which has 0 outgoing edges and n-1 incoming edges.(at most there can be only one such node)
  15. So in mp[i] we are storing the count of incoming edges in excess to the outgoing edges.
  16. So mp[i] == n-1 means that for node i there are n-1 more incoming edges than outgoing ones, but we know that at any particular node there cannot be more than n-1 total edges (incoming + outgoing), so in this case outgoing edges has to be zero and incoming edges n-1, which is the judge condition.
  17. By the same reasoning all non-judge nodes will have values less than n-1(either due to shortage of incoming edges or presence of outgoing edge)
  18. """
  19. class Solution:
  20.    def findJudge(self, n: int, trust: List[List[int]]) -> int:
  21.        mp = Counter()
  22.        for a, b in trust:
  23.            mp[b] += 1
  24.            mp[a] -= 1
  25.            
  26.        for i in range(1, n+1):
  27.            if mp[i] == n-1:
  28.                return i
  29.        return -1
  30.  
  31. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement