Show problems as
Classic problem #997EasyArrayHash TableGraph Theory

Find the Town Judge

Real-world version: Finding the Trusted Steward
Tracked in this browser only
Read Find the Town Judge on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A hall holds n people numbered 1 through n. Each entry trusts[i] = [a, b] says person a trusts person b, and no entry is listed twice.

The steward is the one person who trusts nobody at all and whom every other person trusts.

Return the steward's number, or -1 when there is none.

Examples

Example 1

Input
n = 1, trusts = []
Output
1

With one person in the hall, that person trusts nobody and there is nobody left who has to trust them, so they are the steward.

Example 2

Input
n = 4, trusts = [[1, 3], [2, 3], [4, 3]]
Output
3

Person 3 trusts nobody, and the other three all trust them, which is exactly what the steward has to be.

Example 3

Input
n = 2, trusts = [[1, 2], [2, 1]]
Output
-1

Each person trusts the other, so neither trusts nobody and there is no steward.

Constraints

  • 1 <= n <= 1000
  • 0 <= trusts.length <= 10^4
  • trusts[i].length == 2
  • 1 <= trusts[i][j] <= n
  • The two people in an entry are different.
  • No entry is listed twice.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def find_judge(n: int, trusts: list[list[int]]) -> int:
Java
public int findJudge(int n, int[][] trusts)