Advertisement
kai-rocket

Find the Town Judge

Jul 30th, 2021
840
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. from collections import defaultdict
  2.  
  3. class Solution:
  4.     def findJudge(self, N: int, trust: List[List[int]]) -> int:
  5.         # If N is 1 and there are no relationships, return 1
  6.         if N == 1 and len(trust) == 0:
  7.             return 1
  8.        
  9.         # Create 2 dictionaries inbound and outbound
  10.         inbound = defaultdict(int)
  11.         outbound = defaultdict(int)
  12.        
  13.         # Iterate through trust array
  14.         for relationship in trust:
  15.             # Extract a_i and b_i
  16.             a_i = relationship[0]
  17.             b_i = relationship[1]
  18.             # Increment a_i in outbound dict
  19.             outbound[a_i] += 1
  20.             # Increment b_i in inbound dict
  21.             inbound[b_i] += 1
  22.        
  23.         # Iterate through inbound dict:
  24.         for k, v in inbound.items():
  25.             # If N-1 in inbound value for key k
  26.             if v == N-1:
  27.                 # If the value for key k is 0 in outbound
  28.                 if outbound[k] == 0:
  29.                     # Return town judge if any.
  30.                     # Not possible to have 2 nodes that both satisfy town judge requirements.
  31.                     return k
  32.        
  33.         # If no town judge, return -1
  34.         return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement