Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Graphs

Find the Town Judge

EASY✓ CHIP-TIMEDLC #997 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Among n townspeople labeled 1 through n, each [a, b] entry means a trusts b. Find the person that every other townsperson trusts while trusting no one back — the town judge — or report −1 if no one fits.

A town of n people, numbered 1 through n, has a list of trust statements shaped [a, b], meaning person a trusts person b. Somewhere in that town might sit a judge: someone every other person trusts, who trusts nobody in return.

The judge, if one exists, is unique — there's exactly one person satisfying both conditions or nobody does. Trust statements don't include self-trust, and a pair can't repeat, so the raw list is enough to work from directly.

The answer is that person's number, or −1 if no single townsperson trusts nobody while being trusted by literally everyone else.

  • 1 to a few thousand townspeople
  • trust list length scales with the number of people, not fixed
  • no person trusts themselves, and no trust pair repeats
  • at most one judge can exist — never a tie between two people
EX 01
n = 2 · trust = [[1, 2]]
→ 2
one trusts the other
EX 02
n = 1 · trust = []
→ 1
single person is trivially the judge
EX 03
n = 3 · trust = [[1, 3], [2, 3]]
→ 3
trusted by everyone else

The hintstake only what you need

HINT 1 THE NUDGE

Only two facts about a person matter: how many people trust them, and how many people they trust. What must those two numbers look like for the judge?

HINT 2 THE STRUCTURE

The judge is trusted by everyone else (n−1 incoming trusts) and trusts nobody (zero outgoing trusts). A single running score per person — trusted-count minus trusts-count — captures both at once.

HINT 3 ONE STEP FROM THE ANSWER

For each pair [a, b], add 1 to b's score and subtract 1 from a's score. The judge, if one exists, is the only person left with a score of exactly n−1.

Coach's boardthe pattern, step by step

THE NET SCOREPATTERN · ONE SCORE ARRAYn = 4 people · trust: 1→3, 1→4, 2→3, 2→4, 4→3
STEP 1

Score = trusted-count minus trusts-count. Every [a,b] pair does score[a]-1, score[b]+1. The judge ends at exactly n−1 = 3.

STEP 1 / 8 · ← → WORK TOO

The splitstwo paces, two languages

grind/find-the-town-judge.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def findJudge(self, n: int, trust: List[List[int]]) -> int:
        score = [0] * (n + 1)
        for a, b in trust:
            score[a] -= 1
            score[b] += 1
        for person in range(1, n + 1):
            if score[person] == n - 1:
                return person
        return -1
TIME O(N+M)SPACE O(N)PYTHON · RACE PACE · 10 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED