Problem 582559 · easy · Level 05 Advanced Algorithms & Graphs

Who Does the Whole Village Trust?

graphs · degrees · directed graph

A village has n residents labelled 1 .. n. Gossip says one of them is the village elder (the judge the function looks for): someone every other resident trusts who in turn trusts nobody. At most one resident can fit that description. Each entry trust[i] = [a, b] records that resident a trusts resident b. Return the elder's label, or -1 if no resident fits.

Examples

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

Input:  n = 4, trust = [[1,3],[2,3]]
Output: -1
Explanation: resident 4 does not trust 3, so nobody is trusted by everyone else.

Input:  n = 4, trust = [[1,4],[2,4],[3,4],[1,2]]
Output: 4
Explanation: the others may trust each other too; only the judge must trust nobody.

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…