DSA Graphs

Find the Town Judge

A judge has in-degree n-1 and out-degree 0 — one pass through trust counts both.

Easy
Time O(n + E) Space O(n)
LeetCode
3 min read
graph in-degree

Problem#

In a town with n people, the judge trusts no one and is trusted by everyone else. Given a list of trust edges [a, b] meaning a trusts b, return the judge’s label, or -1 if no such person exists.

Examples#

  • n = 2, trust = [[1,2]]2
  • n = 3, trust = [[1,3],[2,3]]3
  • n = 3, trust = [[1,3],[2,3],[3,1]]-1

Constraints#

  • 1 <= n <= 1000, 0 <= trust.length <= 10^4.

Approach#

For each trust [a, b], decrement score[a] and increment score[b]. The judge will end with score n - 1.

Solution#

Find the Town Judge
class Solution {
public:
int findJudge(int n, vector<vector<int>>& trust) {
vector<int> score(n + 1, 0);
for (auto& t : trust) {
score[t[0]]--;
score[t[1]]++;
}
for (int i = 1; i <= n; ++i)
if (score[i] == n - 1) return i;
return -1;
}
};

Editorial#

Net score collapses in-degree and out-degree into one counter. The judge has +1 from every other person (n - 1) and 0 outgoing (no -1). Nobody else can reach n - 1 because at minimum, they trust someone (the judge), costing them -1.

Complexity#

  • Time: O(n + E).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.