Problem 582559 · easy · Phase 05 Advanced Algorithms & Graphs

Who Is the Town Judge?

graphs · degrees · directed graph

In a town of n people labelled 1 .. n, one person may secretly be the town judge. The judge trusts nobody, everybody else trusts the judge, and there is exactly one person with both properties. You are given a list trust where trust[i] = [a, b] means person a trusts person b. Return the label of the judge, or -1 if there is none.

Examples

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

Input:  n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Explanation: 3 is trusted by everyone but also trusts 1.

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

Constraints

  • 1 <= n <= 1000, 0 <= len(trust) <= 10**4
  • All pairs are distinct and a != b.
  • Target O(n + len(trust)) time.

Goals

  • Translate a story into in-degree and out-degree conditions
  • Count degrees in one pass over the edge list
Starting Python…