Skip to main content

Find the Town Judge - LeetCode Daily Challenge

Prerna Sharma

Problem Statement

In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

  1. The town judge trusts nobody.
  2. Everybody (except for the town judge) trusts the town judge.
  3. There is exactly one person that satisfies properties 1 and 2.

You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.

Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.

Example 1

Input: n = 2, trust = [[1,2]]
Output: 2

Example 2

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

Try here before watching the video.

Video Solution

Java Code

class Solution {
    public int findJudge(int n, int[][] trust) {
        int[] degree = new int[n + 1];

        for(int[] trustPair : trust) {
            degree[trustPair[0]] -= 1;
            degree[trustPair[1]] += 1;
        }

        for(int i = 1; i <= n; i++) {
            if(degree[i] == (n - 1)) {
                return i;
            }
        }

        return -1;
    }
}

C++ Code

#include <vector>

using namespace std;

class Solution {
public:
    int findJudge(int n, vector<vector<int>>& trust) {
        vector<int> degree(n + 1);

        for (const auto& trustPair : trust) {
            degree[trustPair[0]]--;
            degree[trustPair[1]]++;
        }

        for (int i = 1; i <= n; i++) {
            if (degree[i] == (n - 1)) {
                return i;
            }
        }

        return -1;
    }
};

Python Code

class Solution:
    def findJudge(self, n: int, trust: List[List[int]]) -> int:
        degree = [0] * (n + 1)

        for trustPair in trust:
            degree[trustPair[0]] -= 1
            degree[trustPair[1]] += 1

        for i in range(1, n + 1):
            if degree[i] == n - 1:
                return i

        return -1

Javascript Code

var findJudge = function(n, trust) {
    const degree = new Array(n + 1).fill(0);

    for (const trustPair of trust) {
        degree[trustPair[0]]--;
        degree[trustPair[1]]++;
    }

    for (let i = 1; i <= n; i++) {
        if (degree[i] === n - 1) {
            return i;
        }
    }

    return -1;
};

Go Code

func findJudge(n int, trust [][]int) int {
    degree := make([]int, n+1)

    for _, trustPair := range trust {
        degree[trustPair[0]]--
        degree[trustPair[1]]++
    }

    for i := 1; i <= n; i++ {
        if degree[i] == n-1 {
            return i
        }
    }

    return -1
}

Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(n)