Problem Description
Given n people labeled from 1 to n and an array trust where trust[i] = [a, b] indicates that person a trusts person b, determine if there is a town judge. The town judge trusts nobody and is trusted by everyone else (n-1 people). Return the label of the town judge if they exist, otherwise return -1.
Key Insights
- Use in-degree and out-degree concepts from graph theory.
- The town judge (if exists) will have 0 out-degree (trusts nobody) and an in-degree of n-1 (trusted by everyone else).
- An efficient one-pass accumulation can be employed by maintaining a score for each person computed as in-degree minus out-degree.
Space and Time Complexity
Time Complexity: O(n + m) where m is the number of trust relationships. Space Complexity: O(n) for tracking the net trust scores or degrees for each individual.
Solution
We can solve the problem by keeping track of how many people trust each individual and how many people each individual trusts. For every trust pair [a, b], decrement the trust score for a (since a trusts someone) and increment the trust score for b (since b is trusted). The town judge will then be the person whose trust score equals n-1, implying they are trusted by all other n-1 people and do not trust anyone at all.