Community Problem

Find the Town Judge

Difficulty: Easy

Identify the unique person trusted by everyone but trusts nobody, using in-degree minus out-degree.

Find the Town Judge

Identify the unique person trusted by everyone but trusts nobody, using in-degree minus out-degree.

EASY
Free
graphs
graph-representation
hash-table
chidiweber

By @chidiweber

April 26, 2026

·

Updated May 20, 2026

606 views

10

4.3 (9)

I had this on a junior phone screen and was struck by how cleanly it teaches "sometimes a graph problem is just a counting problem". The trick is to realize that "trusted by everyone but trusts nobody" is exactly the in-degree minus out-degree equals n - 1 condition. Once you see that, you do not need an adjacency list at all. The catalog covers Graph Representation but skipped this degree-based identifier.

Find the Town Judge

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:

  1. The town judge trusts nobody.
  2. Everybody (except for the town judge) trusts the town judge.
  3. There is exactly one person that satisfies properties 1 and 2.

You are given an array trust where trust[i] = [a_i, b_i] representing that person a_i trusts person b_i. If a trust relationship does not exist in trust, then it does not exist.

Return the label of the town judge if they exist, otherwise return -1.

Examples

Example 1:

  • Input: n = 2, trust = [[1, 2]]
  • Output: 2
  • Explanation: Person 1 trusts person 2. Person 2 trusts nobody. So 2 is the judge.

Example 2:

  • Input: n = 3, trust = [[1, 3], [2, 3]]
  • Output: 3
  • Explanation: Both 1 and 2 trust 3, and 3 trusts nobody.

Example 3:

  • Input: n = 3, trust = [[1, 3], [2, 3], [3, 1]]
  • Output: -1
  • Explanation: 3 also trusts 1, so 3 cannot be the judge.

Example 4:

  • Input: n = 1, trust = []
  • Output: 1
  • Explanation: With one person, they vacuously satisfy both conditions.

Constraints

  • 1 <= n <= 1000.
  • 0 <= trust.length <= 10^4.
  • trust[i].length == 2.
  • All the pairs of trust are unique.
  • a_i != b_i.
  • 1 <= a_i, b_i <= n.

Follow-up

Why is the score-based one-pass solution correct? The judge has in-degree n - 1 and out-degree 0, so score = (n - 1) - 0 = n - 1. No other person can have a higher score because the maximum out-degree-zero person has at most in-degree n - 1 (everyone but themselves), and any out-trust strictly lowers the score. Uniqueness follows from score == n - 1 being achieved by at most one person.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems