Statement▼
There are n people numbered from n in a town. There’s a rumor that one of these people is secretly the town judge. A town judge must meet the following conditions:
The judge doesn’t trust anyone.
Everyone else in the town (except the town judge) trusts the judge.
There is exactly one person who fulfills both the above conditions.
You are given an integer n and a two-dimensional array, trust, where each entry trust array, it does not exist. Your task is to determine the label of the town judge, if one can be identified. If no such person exists, return
Constraints:
1≤ n≤1000 0≤ trust.length≤104 trust[i].length==2 ai= bi1≤ ai,bi≤ nAll the pairs in
trustare unique.
Solution
This algorithm to find the town judge is based on the graph representing trust relationships, where each person is a vertex and directed edges show the trust between them. To solve the problem, the algorithm uses two arrays: one for the indegree and another for the outdegree of each person. In graphs, the outdegree of a vertex (person in this case) refers to the connections going out from it (how many people they trust), and the indegree of a vertex refers to connections coming in (how many people trust them).
To find the judge, the algorithm searches for the person whose indegree is exactly n - 1, which indicates that everyone else trusts that person, and whose outdegree is
The algorithm to solve this problem is as follows:
If the length of the
trustrelationship is less thann - 1, it means that not all persons trust someone, we will return-1in this case.Create two arrays
indegreeandoutdegree, to count the indegree and outdegree of a person, respectively:Loop through the
trustarray, which contains pairs[a,b] , and for each pair:Increase the
outdegree[a]by1 , because persona is trusts someone.Increase the
indegree[b]by1 , because personb is trusted by someone.
After processing the trust relationships, iterate over
indegreeandoutdegreearrays and check if a person’s indegree is exactlyn - 1, which means all other people trust them. The outdegree of that person should also be exactly0 , which means that the person does not trust anybody. If such a person is found, we will return its index.After the loop terminates, return
-1, which indicates that there is no judge.
Let’s look at the following illustration to get a better understanding of the solution: