AAlgoLoopSpaced repetition for LeetCode
EASYGraphLeetCode ↗

Find the Town Judge

The key idea

The judge is trusted by everyone else and trusts nobody. Give each person +1 when someone trusts them and -1 when they trust someone. The judge is the one and only person whose net score equals n - 1.

Problem

In a town of n people labeled from 1 to n, there is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

1. The town judge trusts nobody.
2. Everybody (except the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties 1 and 2.

You are given an array trust where trust[i] = [a, b] means that the person labeled a trusts the person labeled b. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.

Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.

Constraints

Examples

Input: n = 2, trust = [[1,2]] Output: 2
Input: n = 3, trust = [[1,3],[2,3]] Output: 3
Input: n = 3, trust = [[1,3],[2,3],[3,1]] Output: -1

Complexity

Time: O(n + e) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Graph problems