Find the Town Judge

A town has n people labeled 1 to n, and one of them may secretly be the town judge. The judge trusts nobody, everybody else trusts the judge, and exactly one person fits both rules. Given trust, where trust[i] = [a, b] means person a trusts person b, return the judge's label, or -1 if there is no judge.

30:00

Find the Town Judge
easy
Free written solution
Topics
Companies

A town has n people labeled 1 to n, and one of them may secretly be the town judge. The judge trusts nobody, everybody else trusts the judge, and exactly one person fits both rules. Given trust, where trust[i] = [a, b] means person a trusts person b, return the judge's label, or -1 if there is no judge.

Example 1:
Input: {"n":2,"trust":[[1,2]]}
Output: 2
Constraints:
  • 1≤n≤10001 \leq n \leq 1000

  • 0≤trust.length≤1040 \leq \text{trust.length} \leq 10^4

  • trust[i].length==2\text{trust}[i].\text{length} == 2

  • All the pairs of trust are unique.

  • ai≠bia_i \neq b_i

  • 1≤ai,bi≤n1 \leq a_i, b_i \leq n

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":2,"trust":[[1,2]]}

2 people and 1 trust pair. Each score starts at 0: trusting someone costs 1, being trusted earns 1.

1→2

1020

score = trusted by - trusts

judge needs 1

#1

0 / 0

0

#2

0 / 0

0

trusted by

trusts

being checked

judge

Variables
VariableValue
n2
trust.length1
DepthFunction Call
Stack empty
0/4