Find the Town Judge Visualizer & Step-by-Step Algorithm Solution

Track incoming trust minus outgoing trust for each person, then find the person whose score equals n − 1.

Category: graphs | Difficulty: Easy

Tags: Graph, Array, In-Degree, Out-Degree

Find the Town Judge

Drag nodes to arrange
Trust · 2 people · 1 edges · a → b means a trusts b
1
score: 0
2
score: 0
score = incoming − outgoing · index 0 unused
0
0
0
1
0
2
100%
state
n2
n - 11
Initialize Scores
1/8
Explanation

Create score with 3 zeroes. People use indices 1 through 2; index 0 is unused. The judge must finish with score n − 1 = 1.

Source Code
1function findJudge(n: number, trust: number[][]): number {
2 const score = new Array(n + 1).fill(0);
3 for (let [a, b] of trust) {
4 score[a]--;
5 score[b]++;
6 }
7 for (let i = 1; i <= n; i++) {
8 if (score[i] === n - 1) return i;
9 }
10 return -1;
11}