Who Everyone Trusts

EasyGraphs≈ 15 min

A town has n people, numbered from 0 to n − 1. Who trusts whom is given as two lists of the same length: person truster[i] trusts person trusted[i]. Trust goes one way: it does not mean the second person trusts the first.

Find the person who is trusted by everyone else and trusts nobody. Return their number, or -1 if there is no such person. There can never be two.

Examples

text
n = 3, truster = [0, 1], trusted = [2, 2]                       →  2
n = 3, truster = [0, 1, 2], trusted = [2, 2, 0]                 →  -1
n = 1, truster = [], trusted = []                               →  0
n = 4, truster = [0, 1, 2, 0, 3], trusted = [3, 3, 3, 1, 1]     →  -1

In the second example everyone trusts 2, but 2 trusts 0. In the last, 3 is trusted by everyone else but trusts 1. A town of one person has nobody else to be trusted by, so that person counts.

Constraints

  • Between 1 and 10,000 people and up to 20,000 trusts; no one trusts themselves, and no trust is listed twice.
  • Aim for O(n + m), n people and m trusts.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.