Skip to main content

Find the Town Judge

Easy
Data Structures and Algorithms
Editorial
Topics:
Graph
Array
Counting

There are n people, identified by the integers from 1 through n. Each inner array in trust has the form [a, b], meaning person a trusts person b.

A town judge is a person who trusts nobody, while every other person trusts the judge. Determine whether such a person exists. If it exists, return that person's label; otherwise, return -1.

Implement findJudge in the Solution class with the given signature. The input may describe no trust relationships, and the requirements must hold for all people exactly as stated.

Example 1:

Input: n = 4, trust = [[1,3],[2,3],[4,3]]
Output: 3
Explanation: Person 3 trusts nobody, and each of the other three people trusts person 3, so person 3 is the judge.

Example 2:

Input: n = 3, trust = [[1,2],[2,3]]
Output: -1
Explanation: Although person 3 is trusted by person 2, person 1 does not trust person 3, so no one satisfies both judge conditions.

Example 3:

Input: n = 1, trust = []
Output: 1
Explanation: With only one person, that person trusts nobody and there are no other people who need to trust the judge.

Constraints:

  • 1 <= n <= 1000
  • 0 <= trust.length <= 10^4
  • trust[i].length == 2
  • 1 <= trust[i][0] <= n
  • 1 <= trust[i][1] <= n
  • trust[i][0] != trust[i][1]
  • All pairs in trust are unique

Need help or want more practice?

Practise in an interviewGet AI Coach help