MediumNo. 0614LeetCode Premium
Second Degree Follower — LeetCode 614 Python Solution
- Topics
- Database
- Reading time
- 3 min
- Source
- leetcode.com
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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0610 | Triangle Judgement | Easy |
| 0619 | Biggest Single Number | Easy |
| 0608 | Tree Node | Medium |
| 0620 | Not Boring Movies | Easy |
| 0607 | Sales Person | Easy |
| 0175 | Combine Two Tables | Easy |
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.