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
Difficulty
and has an acceptance rate of about 51% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Graph Theory
- Hash Table
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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 |
Videos
Similar Problems
- problem 277: Find the Celebrity
Solved On The Same Day
- problem 695: Max Area of Island
- problem 797: All Paths From Source to Target
- problem 802: Find Eventual Safe States
- problem 863: All Nodes Distance K in Binary Tree
- problem 934: Shortest Bridge
- problem 1020: Number of Enclaves
- problem 1091: Shortest Path in Binary Matrix
- problem 1129: Shortest Path with Alternating Colors
- problem 1306: Jump Game III
- problem 1376: Time Needed to Inform All Employees
- problem 1557: Minimum Number of Vertices to Reach All Nodes
- problem 2038: Remove Colored Pieces if Both Neighbors are the Same Color
- problem 212: Word Search II
Extra
- 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