Find the town judge
Graph
easy
Score: 20
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:
- The town judge trusts nobody.
- Everybody (except for the town judge) trusts the town judge.
- There is exactly one person that satisfies properties 1 and 2.
You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi .
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
Input Format
First Parameter : n
, no of people in row
Second Parameter: trust
, 2d array representing trust between people
Output Format
Return label
of town judge if exists else return -1
.
Example 1:
Input:
2
1 2
1 2
Output:
2
explanation: 1 2 represents the size of the matrix trust.
Example 2:
Input:
3
2 2
1 3
2 3
Output:
3
explanation: 2 2 represents the size of the matrix trust.
Example 3:
Input:
3
3 2
1 3
2 3
3 1
Output:
-1
explanation: 3 2 represents the size of the matrix trust.
Constraints :
- 1 <= n <= 103.
- 0 <= trust.length (number of rows) <= 104.
- trust[i].length == 2.
- All the pairs of
trust
are unique. - *ai != bi *
- 1 <= ai , bi <= n .
- Expected Time Complexity: O(n)
- Expected Space Complexity: O(n).