Second Degree Follower — LeetCode 614 Python Solution

MediumLeetCode PremiumDatabase
Problem
#614
Reading time
3 min

The problem

A second-degree follower is a user who follows somebody and is also followed by somebody. Report every second-degree follower with the number of followers they have, ordered by name. The Follow table has one row per relationship: followee (varchar) and follower (varchar), meaning that follower follows followee, with the pair as the primary key. Nobody follows themself.

Example

Follow table:

| followee | follower |
| -------- | -------- |
| Maya     | Noah     |
| Noah     | Omar     |
| Noah     | Priya    |
| Priya    | Quinn    |

Result:

| follower | num |
| -------- | --- |
| Noah     | 2   |
| Priya    | 1   |

Noah follows Maya and is followed by Omar and Priya, and Priya follows Noah and is followed by Quinn; Omar and Quinn follow somebody but have no followers, and Maya has a follower but follows nobody.

Python solution

Python
import pandas as pd

def second_degree_follower(follow: pd.DataFrame) -> pd.DataFrame:
    active = set(follow['follower'])
    res = (
        follow[follow['followee'].isin(active)]
        .groupby('followee')['follower']
        .nunique()
        .reset_index()
    )
    res.columns = ['follower', 'num']
    return res.sort_values('follower')

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 614. Second Degree Follower?
LeetCode 614. Second Degree Follower is rated Medium on LeetCode.
What topics does LeetCode 614. Second Degree Follower cover?
LeetCode 614. Second Degree Follower is tagged Database on LeetCode.
Is LeetCode 614. Second Degree Follower a premium problem?
Yes. LeetCode 614. Second Degree Follower is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview