Find the Town Judge
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
trust
, an array of pairs trust[i] = [a, b]
representing that the person labeled a
trusts the person labeled b
.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return
-1
.Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] Output: 3Let's understand the problem, we have an array of people where the 0th index person will trust the 1st index person. Any person with maximum trust N - 1 will be town judge and return the label if not then return -1.
In the above input of trust, 1st person is trusting on 3rd and 4th person. Each person has a judge count and it will increase if a person trusts on him and decrease if he trusts on someone by 1 for each person. It is a very straightforward and simple data structure problem. Let's take a look at the code.
public int findJudge(int N, int[][] trust) { int[] judgeCount = new int[N + 1]; for (int[] person : trust) { judgeCount[person[0]]--; judgeCount[person[1]]++; } for (int i = 1; i <= N; i++) { if (judgeCount[i] == N - 1) { return i; } } return -1; }
Comments
Post a Comment