LeetCode 997: Find the Town Judge Solution

Master LeetCode problem 997 (Find the Town Judge), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

997. Find the Town Judge

Problem Explanation

Explanation:

To solve this problem, we can create two arrays: trustCount and isTrusted. The trustCount array will store the count of people trusting each person, and the isTrusted array will store whether a person trusts someone or not.

We will iterate through the trust array and update these arrays. After that, we will check for the person who is trusted by all others (trustCount[i] == n-1) and doesn't trust anyone (isTrusted[i] == false). This person will be considered as the town judge. If there is no such person, we return -1.

  • Time complexity: O(N), where N is the number of people in the town.
  • Space complexity: O(N) for the two arrays.

:

Solution Code

class Solution {
    public int findJudge(int n, int[][] trust) {
        int[] trustCount = new int[n+1];
        boolean[] isTrusted = new boolean[n+1];
        
        for (int[] t : trust) {
            int a = t[0];
            int b = t[1];
            trustCount[b]++;
            isTrusted[a] = true;
        }
        
        for (int i = 1; i <= n; i++) {
            if (trustCount[i] == n-1 && !isTrusted[i]) {
                return i;
            }
        }
        
        return -1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 997 (Find the Town Judge)?

This page provides optimized solutions for LeetCode problem 997 (Find the Town Judge) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 997 (Find the Town Judge)?

The time complexity for LeetCode 997 (Find the Town Judge) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 997 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 997 in Java, C++, or Python.

Back to LeetCode Solutions