Problem statement

https://leetcode.com/problems/find-the-town-judge/

Solution

For each person let us add -1 if it trusts someone and +1 if someone else trust this person. Then the judge is the person with value n - 1.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def findJudge(self, N, trust):
        if not trust and N == 1:
            return 1
        cands = [0] * (N+1)
        for elem1, elem2 in trust:
            cands[elem2] += 1
            cands[elem1] -= 1
            
        return cands.index(N-1) if N-1 in cands else -1