Problem 997

Abstract / Summary

A town judge is someone trusted by everyone else but trusts no one find such a person in a town.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0997.py

class Solution:
    def findJudge(self, n: int, trust: List[List[int]]) -> int:
        # convert edges to sets
        all = defaultdict(set)
        for a, b in trust:
            all[a].add(b)

        # AND all those sets
        common    = set(range(1, n + 1))
        candidate = None
        numEmpty  = 0
        for i in range(1, n+1):
            if not all[i]:
                numEmpty += 1
                continue

            common &= all[i]
            if not common: # early exit: noone left who is trusted by everybody
                return -1

        # persons who trust noone
        if numEmpty != 1:
            return -1

        # a unique person must be left
        if len(common) != 1:
            return -1
        for c in common: # weird syntax to extract the only element from a set
            return c
29 lines | 867 bytes | submitted October 2, 2023 | GitHub   28% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Graph Theory
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation determines the “town judge” in a community of n people given a list of trust relationships. A judge is defined as a person who is trusted by everyone else while trusting nobody. The algorithm builds a representation of outgoing trust edges, intersects the sets of people each trusting individual trusts, and validates that exactly one candidate satisfies the required conditions.

Key Steps

Building the adjacency structure

all = defaultdict(set)
for a, b in trust:
    all[a].add(b)

A defaultdict of sets stores, for each person a, the collection of people b that a trusts. This representation enables constant-time insertion and fast set operations later.

Intersecting trust sets to find common targets

common    = set(range(1, n + 1))
candidate = None
numEmpty  = 0
for i in range(1, n+1):
    if not all[i]:
        numEmpty += 1
        continue

    common &= all[i]
    if not common:               # early exit
        return -1

The variable common starts as the full universe of possible judges. For each person who trusts at least one other, the algorithm intersects common with that person’s trust set. If at any point the intersection becomes empty, the function returns -1 immediately, avoiding unnecessary work.

Verifying the count of people who trust nobody

if numEmpty != 1:
    return -1

Only a single individual may have an empty outgoing trust set; otherwise the judge condition cannot be satisfied. This check eliminates cases where multiple people trust nobody or where nobody trusts nobody.

Ensuring a unique candidate remains

if len(common) != 1:
    return -1
for c in common:                 # extract the sole element
    return c

After processing all trust relationships, common must contain exactly one element-the potential judge. The loop extracts that element and returns it. If the set size differs from one, the function signals failure with -1.

Edge Cases Handled

When trust is empty and n equals 1, the single person has no outgoing trust edges, numEmpty becomes 1, common remains the full set {1}, and the function correctly returns 1.

If multiple people have no outgoing trust edges, numEmpty exceeds 1, causing the function to return -1.

When a person trusts everyone else, the intersection quickly narrows to the common target(s); if no single person is trusted by all, the early-exit condition triggers, returning -1.

If the trust list contains contradictory information that eliminates all possible judges, the early exit after an empty intersection returns -1 without scanning the remainder of the list.

Performance Optimizations

The use of a defaultdict(set) provides O(1) amortized insertion for each trust pair, avoiding the overhead of checking key existence.

Set intersection (common &= all[i]) reduces the candidate pool incrementally; the algorithm stops as soon as the candidate set empties, preventing further unnecessary intersections.

Counting people with empty outgoing trust sets (numEmpty) while iterating eliminates a separate pass over the data structure.

The final extraction of the sole element from common uses a simple loop over the set, which is efficient because the set size is guaranteed to be one at that point.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a group of people in a room who are trying to find one special person. This special person is someone that everyone else trusts, but this special person does not trust anyone at all.

To solve this, the code first gathers all the information about who trusts whom and puts that into a big list. It looks at every single person and keeps a record of who they provide their trust to.

Next, the code starts looking for the one person who fits the rules. It gathers a group of all the people who could potentially be the special person. As it checks each name, if it discovers that someone trusts other people, that person cannot possibly be the special one, so they are removed from the possibilities.

The code also counts how many people do not trust anyone. If there is more than one person who trusts nobody, or if nobody trusts nobody, then the rules are not met.

Finally, after looking at all the information, the code checks if there is exactly one person left who is trusted by everyone and trusts no one. If everything matches up perfectly, that person is declared the winner.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.26 | σ = 1.65

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
pruthvikp Python
qiyuangong Python
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
pruthvikp Python
qiyuangong Python
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
43 links | 29 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

14 solutions   October 2, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality