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. If there is a town judge, they must meet these conditions:
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 (except the judge) trusts the judge.
Only one person in the town can meet both of these conditions.
Given there is n
and a two-dimensional array called trust
, each element trust[i]
has two elements a
trusts person b
. If there is a judge, return their number, 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.