SDE & MLE Prep

997. Find the Town Judge

Problem

In a town of people 1…n, the judge (if any) trusts nobody and is trusted by everyone else, and at most one person fits. trust[i] = [a, b] means a trusts b. Return the judge's label, or −1.

Example: n = 3, trust = [[1,3],[2,3]] → 3; n = 3, trust = [[1,3],[2,3],[3,1]] → -1

The judge is trusted by everyone else (in-degree n − 1) and trusts nobody (out-degree 0). One score per person, in − out, equals n − 1 only for the judge.

Complexity: O(n + |trust|).

class Solution:
    def findJudge(self, n: int, trust: List[List[int]]) -> int:
        score = [0] * (n + 1)
        for a, b in trust:
            score[a] -= 1
            score[b] += 1
        return next((p for p in range(1, n + 1) if score[p] == n - 1), -1)