+-------------+------+
|Column Name |Type|+-------------+------+
| user_id | int || follower_id | int |+-------------+------+
(user_id, follower_id) is the primarykey (combination of columns withuniquevalues) for this table.
Eachrowof this table indicates that the userwith ID follower_id is following the userwith ID user_id.
Write a solution to find all the pairs of users with the maximum number of common followers. In other words, if the maximum number of common followers between any two users is maxCommon, then you have to return all pairs of users that have maxCommon common followers.
The result table should contain the pairs user1_id and user2_id where user1_id < user2_id.
Input:
Relations table:
+---------+-------------+
| user_id | follower_id |+---------+-------------+
|1|3||2|3||7|3||1|4||2|4||7|4||1|5||2|6||7|5|+---------+-------------+
Output:
+----------+----------+
| user1_id | user2_id |+----------+----------+
|1|7|+----------+----------+
Explanation:
Users 1and2 have two common followers (3and4).
Users 1and7 have three common followers (3, 4, and5).
Users 2and7 have two common followers (3and4).
Since the maximum number of common followers betweenany two users is3, we returnall pairs of users with three common followers, which isonly the pair (1, 7). We return the pair as (1, 7), notas (7, 1).
Note that we donot have any information about the users that follow users 3, 4, and5, so we consider them to have 0 followers.
The key idea is to find all pairs of users who share the same followers. By joining the table with itself on follower_id, we can count how many followers two users have in common. Then, we select the pairs with the maximum count.
WITH CommonFollowers AS (
SELECT r1.user_id AS user1_id,
r2.user_id AS user2_id,
COUNT(*) AS common_count
FROM Relations r1
JOIN Relations r2
ON r1.follower_id = r2.follower_id
AND r1.user_id < r2.user_id
GROUPBY r1.user_id, r2.user_id
),
MaxCommon AS (
SELECTMAX(common_count) AS max_common
FROM CommonFollowers
)
SELECT user1_id, user2_id
FROM CommonFollowers, MaxCommon
WHERE common_count = max_common;