Find the Town Judge

easy graph hash map

Problem

Given n people (1..n) and a list of trust pairs [a, b] meaning a trusts b, return the town judge (trusted by everyone, trusts no one) or -1.

Inputn=3, trust=[[1,3],[2,3]]
Output3
score[b]++ and score[a]−−; judge has score n − 1.

def findJudge(n, trust):
    score = [0] * (n + 1)
    for a, b in trust:
        score[a] -= 1
        score[b] += 1
    for i in range(1, n + 1):
        if score[i] == n - 1: return i
    return -1
function findJudge(n, trust) {
  const score = new Array(n + 1).fill(0);
  for (const [a, b] of trust) { score[a]--; score[b]++; }
  for (let i = 1; i <= n; i++) if (score[i] === n - 1) return i;
  return -1;
}
class Solution {
    public int findJudge(int n, int[][] trust) {
        int[] score = new int[n + 1];
        for (int[] t : trust) { score[t[0]]--; score[t[1]]++; }
        for (int i = 1; i <= n; i++) if (score[i] == n - 1) return i;
        return -1;
    }
}
int findJudge(int n, vector<vector<int>>& trust) {
    vector<int> score(n + 1, 0);
    for (auto& t : trust) { score[t[0]]--; score[t[1]]++; }
    for (int i = 1; i <= n; i++) if (score[i] == n - 1) return i;
    return -1;
}
Time: O(n + E) Space: O(n)