Everyone follows them
With one-way edges, count arrows in and arrows out separately. About 10 minutes.
Two counts per person
With arrows, "how connected is this person?" splits into two questions. How many arrows point at them? Those are their followers. How many arrows leave them? That is how many people they follow.
Read each arrow once: it leaves the person who follows, and lands on the person being followed. So one pass over the arrows gives both counts.
followers = [0] * n
following = [0] * n
for a, b in follows:
following[a] += 1
followers[b] += 1
for person in range(n):
if followers[person] != n - 1:
continue
if following[person] == 0:
return person
return -1Four people. Under each one: arrows in (followers) and arrows out (following). All zero so far.
Spotting the influencer
An influencer is followed by everyone else, which is n minus 1 followers, and follows nobody. Both conditions matter: plenty of popular people follow a few others back.
After counting, check each person. There cannot be two influencers, because each would have to follow the other.
n = 3, follows = [[0, 2], [1, 2], [2, 0]]. Who is the influencer?
- ANobody (-1)
- BPerson 2
- CPerson 0
Show the answer
Nobody (-1). 2 has both others as followers, but 2 follows 0, so it fails the "follows nobody" rule.
Everyone follows them
A group chat has n people numbered 0 to n - 1. follows lists one-way follows: [a, b] means a follows b. An influencer is followed by every other person and follows nobody. Return the influencer's number, or -1 if there isn't one.
n = 3, follows = [[0, 2], [1, 2]] → 2
1 ≤ n ≤ 100,000 · 0 ≤ follows.length ≤ 100,000 · 0 ≤ a, b < n · a ≠ b · no follow appears twice