Solution: Find the Town Judge
Let's solve the Find the Town Judge problem using the Graphs pattern.
We'll cover the following
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:
n
trust.length
trust[i].length
a
i
b
i
a
i
,b
i
n
All the pairs in
trust
are 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
trust
relationship is less thann - 1
, it means that not all persons trust someone, we will return-1
in this case.Create two arrays
indegree
andoutdegree
, to count the indegree and outdegree of a person, respectively:Loop through the
trust
array, which contains pairs, and for each pair: Increase the
outdegree[a]
by, because person is trusts someone. Increase the
indegree[b]
by, because person is trusted by someone.
After processing the trust relationships, iterate over
indegree
andoutdegree
arrays 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 exactly, 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:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.