Grokking Graph Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Find the Town Judge (easy)
On this page

Problem Statement

Examples

Try it yourself

Problem Statement

You are given a town with n people, labeled from 1 to n. Some people trust others. You need to find out if there is a "town judge". The town judge is someone who:

  1. Everyone else trusts.
  2. The town judge trusts nobody.

Given n and an array trust, where trust[i] = [a<sub>i</sub>, b<sub>i</sub>] means person a<sub>i</sub> trusts person b<sub>i</sub>, return the label of town judge. If there is no town judge, return -1.

Examples

Example 1:

  • Input: n = 4, trust = [[1, 2], [3, 2], [4, 2]]
  • Expected Output: 2
  • Justification: Person 2 is trusted by persons 1, 3, and 4, and person 2 trusts no one. Hence, person 2 is the town judge.

Example 2:

  • Input: n = 3, trust = [[1, 3], [2, 3]]
  • Expected Output: 3
  • Justification: Person 3 is trusted by persons 1 and 2, and person 3 trusts no one. Hence, person 3 is the town judge.

Example 3:

  • Input: n = 3, trust = [[1, 3], [2, 1], [3, 1]]
  • Expected Output: -1
  • Justification: Person 1 is trusted by persons 2 and 3, but person 1 also trusts person 3. Thus, there is no town judge.

Constraints:

  • 1 <= n <= 1000
  • 0 <= trust.length <= 10<sup>4</sup>
  • trust[i].length == 2
  • All the pairs of trust are unique.
  • a<sub>i</sub> != b<sub>i</sub>
  • 1 <= a<sub>i</sub>, b<sub>i</sub> <= n

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

On this page

Problem Statement

Examples

Try it yourself