Find the Town Judge

Easy GraphArray

Problem

In a town of n people labelled 1..n, the judge trusts no one and everyone else trusts the judge. trust[i] = [a, b] means a trusts b. Return the judge label or -1.

Example 1 Input: n=2, trust=[[1,2]] Output: 2
Example 2 Input: n=3, trust=[[1,3],[2,3]] Output: 3
Example 3 Input: n=3, trust=[[1,3],[2,3],[3,1]] Output: -1

Constraints

Approach — Graphs

This is a Graphs problem. The idea: explore the graph with BFS or DFS, marking nodes visited so you never process one twice. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(V + E) time.

Solution code

Python

class Solution:
    def findJudge(self, 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

Java

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;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Find the Town Judge interactively → ← All solutions