MediumNo. 0614LeetCode Premium

Second Degree Follower — LeetCode 614 Python Solution

Topics
Database
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

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

PythonSolution
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

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0610Triangle JudgementEasy
0619Biggest Single NumberEasy
0608Tree NodeMedium
0620Not Boring MoviesEasy
0607Sales PersonEasy
0175Combine Two TablesEasy

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.

Free to download. Check it runs on your machine, then pick a plan.