Problem
Table: Follow
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| followee | varchar |
| follower | varchar |
+-------------+---------+
(followee, follower) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates that the user follower follows the user followee on a social network.
There will not be a user following themself.
A second-degree follower is a user who:
- follows at least one user, and
- is followed by at least one user.
Write a solution to report the second-degree users and the number of their followers.
Return the result table ordered by follower
in alphabetical order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 - Self Join and Grouping
Intuition
A second-degree follower is someone who both follows someone and is followed by someone. We can find all users who are followers (appear in the follower column) and are also followees (appear in the followee column), then count their followers.
Approach
- Find all users who are both a follower and a followee.
- For each such user, count how many times they appear as a followee (i.e., how many followers they have).
- Return the result ordered by follower name.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N)
(N = number of rows in Follow) - 🧺 Space complexity:
O(U)
(U = number of unique users)