Second Degree Follower Problem
Description
LeetCode Problem 614.
In facebook, there is a follow table with two columns: followee, follower.
Please write a sql query to get the amount of each follower’s follower if he/she has one.
For example:
+-------------+------------+
| followee | follower |
+-------------+------------+
| A | B |
| B | C |
| B | D |
| D | E |
+-------------+------------+
should output:
+-------------+------------+
| follower | num |
+-------------+------------+
| B | 2 |
| D | 1 |
+-------------+------------+
Explaination: Both B and D exist in the follower list, when as a followee, B's follower is C and D, and D's follower is E. A does not exist in follower list.
Note: Followee would not follow himself/herself in all cases. Please display the result in follower's alphabet order.
Solution
Approach: Self Join
We want people who are both a follower (they follow someone) and a followee (someone follows them), together with how many followers they have.
Join Follow to itself:
f1is a row where the person appears asfollower,f2is a row where that same person appears asfollowee, sof2.followeris one of their followers.
The join condition f2.followee = f1.follower keeps only people who appear in both roles. A, who follows nobody, has no f1 row and drops out, and so does E, whom nobody follows.
A person who follows several people has several f1 rows, and each of them would repeat their followers. COUNT(DISTINCT f2.follower) counts each follower once.
Finally sort by follower, as the problem asks.
The Pandas version keeps the rows whose followee is also somebody's follower, counts the unique followers per followee with nunique(), and sorts by name.
SELECT f1.follower,
COUNT(DISTINCT f2.follower) AS num
FROM Follow AS f1
-- f2 lists the followers of f1.follower.
JOIN Follow AS f2
ON f2.followee = f1.follower
GROUP BY f1.follower
ORDER BY f1.follower;