09 Sept 2026Go / Python / TypeScriptEasy

Find the Town Judge

Find the person trusted by everyone else who trusts nobody.

Give each person one score for incoming trust and minus one for outgoing trust; the judge's final score is n minus one.

complexity

O(n + t) time and O(n) space.

solution files

  • Go find-the-town-judge/solution.go
  • Python find-the-town-judge/solution.py
  • TypeScript find-the-town-judge/solution.ts

Solution files

Gofind-the-town-judge/solution.go
package main

func findJudge(n int, trust [][]int) int {
	score := make([]int, n+1)
	for _, relation := range trust {
		score[relation[0]]--
		score[relation[1]]++
	}
	for person := 1; person <= n; person++ {
		if score[person] == n-1 {
			return person
		}
	}
	return -1
}
Pythonfind-the-town-judge/solution.py
class Solution:
    def findJudge(self, n: int, trust: list[list[int]]) -> int:
        score = [class="syntax-number">0] * (n + class="syntax-number">1)
        for source, target in trust: score[source] -= class="syntax-number">1; score[target] += class="syntax-number">1
        return next((person for person in range(class="syntax-number">1, n + class="syntax-number">1) if score[person] == n - class="syntax-number">1), -class="syntax-number">1)
TypeScriptfind-the-town-judge/solution.ts
function findJudge(n: number, trust: number[][]): number {
  const score = new Array<number>(n + class="syntax-number">1).fill(class="syntax-number">0);
  for (const [from, to] of trust) { score[from] -= class="syntax-number">1; score[to] += class="syntax-number">1; }
  for (let person = class="syntax-number">1; person <= n; person += class="syntax-number">1) if (score[person] === n - class="syntax-number">1) return person;
  return -class="syntax-number">1;
}