#997
Easy Algorithms Find the town judge
Array Hash Table Graph Theory
50.5% acceptance
Feb 25, 2026
6947
633
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:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn find_judge(n: i32, trust: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
let mut in_deg = vec![0i32; n + 1];
let mut out_deg = vec![0i32; n + 1];
for t in &trust { out_deg[t[0] as usize] += 1; in_deg[t[1] as usize] += 1; }
for i in 1..=n { if in_deg[i] == n as i32 - 1 && out_deg[i] == 0 { return i as i32; } }
-1
}
}