 All Problems
Find the Town Judge
easy
graph
arrays
hash table
amazon
google

In a town, there are n people labeled 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 else (except 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] = [ai, bi] representing that person ai trusts person bi.

Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.

Example 1:

Input:
2
1
1 2
Output: 2

Example 2:

Input:
3
3
1 3
2 3
3 1
Output: -1

Constraints:

  • 1 ≤ n ≤ 1000
  • 0 ≤ trust.length ≤ 10⁴
  • All pairs are unique

Input format: First line: n. Second line: number of trust pairs. Then that many lines "a b".

Output format: Judge label or -1.

Run to check your code against the sample cases, or submit to run every case