Find the Town Judge solution explained
To find the town judge, treat each trust pair as a directed edge and give every person a score of edges coming in minus edges going out. The judge trusts nobody and is trusted by the other n - 1 people, so the judge is the only person whose score can reach exactly n - 1; if nobody reaches it, return -1. One pass over the pairs and one pass over the people gives O(n + t) time and O(n) space, where t is the number of pairs.
By Evin JohnPublished 8 min read
The problem in plain words
A village has n residents, numbered 1 to n. You are given a list of pairs [a, b], each meaning resident a trusts resident b. A rumour says one resident is the judge, and the judge has two properties: the judge trusts no one, and every other resident trusts the judge. Return the judge's number if exactly one resident fits, otherwise -1. For this page, pairs are distinct and nobody trusts themselves.
| n | Trust pairs | Answer | Why |
|---|---|---|---|
| 4 | [1, 4], [2, 4], [3, 4], [1, 2] | 4 | Everyone else trusts 4, and 4 trusts nobody. The extra pair 1 to 2 does not matter. |
| 3 | [1, 3], [2, 3], [3, 1] | -1 | 3 has the votes but trusts 1, so 3 is disqualified. |
| 4 | [1, 2], [2, 3], [3, 4] | -1 | A chain: 4 trusts nobody but only 3 trusts 4. |
| 1 | none | 1 | A lone resident trusts nobody and needs zero supporters. |
| 2 | none | -1 | Neither resident is trusted by the other. |
The single-resident case surprises people. With n = 1 the judge needs n - 1 = 0 supporters and must trust nobody, and resident 1 meets both conditions with an empty list.
Why it gets asked
It is an easy graph question, so it often opens a round or appears in a screening call. The interviewer wants to see whether you translate the story into graph terms on your own (people are nodes, trust is a directed edge), whether you notice that two counts per node are all you need, and whether you check the odd inputs: one person, no pairs, a candidate who trusts someone. It also leads into a well-known follow-up where the data is hidden behind a function call.
First answer: test every resident
Go through the residents one by one. For each, scan the pairs to see whether they trust anybody, and count how many pairs point at them. Return the first resident who trusts nobody and has n - 1 supporters. Each resident costs a full scan, so this is O(n · t) time and O(1) extra space. It is a good reference for testing the faster version.
def find_judge_brute(n, trust):
for person in range(1, n + 1):
trusts_someone = any(a == person for a, b in trust)
trusted_by = sum(1 for a, b in trust if b == person)
if not trusts_someone and trusted_by == n - 1:
return person
return -1One pass: count edges in and out
Repeated scanning is the waste. Read the pairs once and keep, for each resident, how many arrows leave them and how many arrive. The judge is the resident with zero outgoing and n - 1 incoming. You can fold both counts into one number: add 1 for each arrow in, subtract 1 for each arrow out. Nobody can be trusted by more than n - 1 others, so a score of n - 1 is only possible with n - 1 arrows in and none out.
def find_judge(n, trust):
score = [0] * (n + 1) # index 0 unused, people are 1..n
for a, b in trust:
score[a] -= 1 # a trusts someone, so a cannot be the judge
score[b] += 1 # b gains one supporter
for person in range(1, n + 1):
if score[person] == n - 1:
return person
return -1Trace the first village. After the four pairs, resident 1 has 0 in and 2 out (score -2), resident 2 has 1 in and 1 out (score 0), resident 3 has 0 in and 1 out (score -1), and resident 4 has 3 in and 0 out (score 3). With n = 4 the target is 3, so the answer is 4. In the second village, resident 3 collects 2 votes but loses one for trusting resident 1, ending at 1, short of the target of 2.
function findJudge(n, trust) {
const inDeg = new Array(n + 1).fill(0);
const outDeg = new Array(n + 1).fill(0);
for (const [a, b] of trust) {
outDeg[a] += 1;
inDeg[b] += 1;
}
for (let p = 1; p <= n; p++) {
if (outDeg[p] === 0 && inDeg[p] === n - 1) return p;
}
return -1;
}Keeping the two counts separate costs one more array but makes the condition read exactly like the definition. Some interviewers prefer it because it survives a change of rules. The single score is shorter. Either is fine if you can say why it works.
The follow-up: a celebrity behind a function
A common twist hides the pairs. People are numbered 0 to n - 1, and the only way to learn anything is to call knows(a, b), which returns whether a knows b. Find the person everyone knows who knows nobody, using as few calls as possible. Building the full table takes about n² calls. Instead, walk a single candidate forward: if the candidate knows the next person, the candidate cannot be the answer, so switch to that person; if not, the next person cannot be the answer, because the true one is known by everyone. After n - 1 calls only one possibility is left, and a second pass checks it in at most 2(n - 1) calls.
def find_celebrity(n, knows):
# knows(a, b) is the only way to look at the data; people are 0..n-1
candidate = 0
for other in range(1, n):
if knows(candidate, other):
candidate = other # a celebrity knows nobody, so candidate is out
for other in range(n):
if other == candidate:
continue
if knows(candidate, other) or not knows(other, candidate):
return -1
return candidateThe verification pass is not optional. The elimination only proves that nobody else can be the answer. It does not prove the survivor is one, for example when there is no such person at all.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Scan every pair for each resident | O(n · t) | O(1) |
| Score array (in minus out) | O(n + t) | O(n) |
| Two degree arrays | O(n + t) | O(n) |
| Celebrity follow-up with knows() | O(n) calls | O(1) |
Edge cases to test
- n = 1 with no pairs: the answer is 1, not -1.
- n = 2 with no pairs: nobody has a supporter, so -1.
- A resident with all the votes who also trusts one person: -1.
- A chain or a cycle where everyone has exactly one supporter.
- Repeated pairs, if the input allows them. Two copies of [1, 3] in a village of 3 would push resident 3 to a score of 2 without resident 2's vote. Deduplicate with a set of pairs first.
Mistakes that show up often
- Checking only the incoming count and forgetting that the judge must trust nobody.
- Sizing the arrays as n when residents are numbered from 1, which skips the last one or crashes.
- Returning -1 for n = 1 because the pair list is empty.
- Using the single score when the input may contain duplicates, without mentioning the risk.
- In the celebrity version, skipping the verification pass after the elimination loop.
How to explain it out loud
Fictional example
- Candidate
- I'll treat each resident as a node and each trust pair as an arrow from the person who trusts to the person trusted.
- Candidate
- The judge then has n minus one arrows coming in and none going out. I can count both in one pass over the pairs.
- Interviewer
- Can you get away with one array?
- Candidate
- Yes, if I add one for each arrow in and subtract one for each arrow out. Nobody can have more than n minus one supporters, so a score of n minus one means full support and zero outgoing trust. That assumes no duplicate pairs, which I'd confirm.
- Candidate
- That's linear in people plus pairs, with one array of size n plus one. For one resident and no pairs, the answer is one.
Related problems
Degree counting is the first step of topological sort, where nodes with zero incoming arrows go first. Before you claim O(n + t), the Big O cheat sheet is a quick reminder of how loops over two inputs add up. For another graph built from a story, see Accounts Merge, and for a counting problem with a tight bound, Majority Element.
Rehearsing it with Natively
If you practice this problem with Natively, you can screenshot the prompt on Mac or Windows and get the degree-count approach and code in its overlay, then compare it with what you wrote. Talk through a mock round out loud and it transcribes both sides, so you can check afterwards whether you mentioned the n = 1 case and the duplicate-pair assumption. See the AI interview assistant for the full feature set.
Questions people ask
How do you solve Find the Town Judge?
Read the trust pairs once and give each person a score: plus one for each person who trusts them, minus one for each person they trust. Return the person whose score equals n - 1, or -1 if nobody reaches it.
What is the time complexity of Find the Town Judge?
O(n + t) time and O(n) space with the score array, where n is the number of people and t the number of trust pairs. Checking each person against every pair is O(n · t).
Why is the answer 1 when n is 1 and there are no pairs?
The judge must trust nobody and be trusted by the other n - 1 people. With one person that means zero supporters, and the lone person trusts nobody, so both conditions hold.
How is Find the Town Judge related to the celebrity problem?
The celebrity problem hides the pairs behind a knows(a, b) call. Walk one candidate forward, replacing it whenever it knows the next person, then verify the survivor. That uses O(n) calls instead of n².
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
