All the Pairs With the Maximum Number of Common Followers - Problem

You are given a table Relations that represents follower relationships between users.

Task: Find all pairs of users that have the maximum number of common followers.

  • A common follower is someone who follows both users in a pair
  • Return pairs (user1_id, user2_id) where user1_id < user2_id
  • Only return pairs with the maximum count of common followers

For example, if the maximum number of common followers between any two users is 3, return all pairs that have exactly 3 common followers.

Table Schema

Relations
Column Name Type Description
user_id PK int ID of the user being followed
follower_id PK int ID of the user who is following
Primary Key: (user_id, follower_id)
Note: Each row indicates that follower_id follows user_id. The combination of user_id and follower_id is unique.

Input & Output

Example 1 — Basic Common Followers
Input Table:
user_id follower_id
1 3
2 3
7 3
1 4
2 4
7 4
1 5
6 5
Output:
user1_id user2_id
1 2
1 7
2 7
💡 Note:

Users 1, 2, and 7 all have followers 3 and 4 in common. Each pair (1,2), (1,7), and (2,7) has 2 common followers, which is the maximum. User 6 only shares follower 5 with user 1, giving them 1 common follower, which is less than the maximum.

Example 2 — Single Pair Maximum
Input Table:
user_id follower_id
1 3
2 3
1 4
2 4
1 5
2 5
6 7
Output:
user1_id user2_id
1 2
💡 Note:

Users 1 and 2 have 3 common followers (3, 4, 5), which is the maximum. User 6 has no common followers with any other user, so only pair (1,2) is returned.

Constraints

  • 1 ≤ user_id ≤ 1000
  • 1 ≤ follower_id ≤ 1000
  • user_id ≠ follower_id (users cannot follow themselves)

Visualization

Tap to expand
Max Common Followers Pairs INPUT Relations Table user_id follower_id 1 3 2 3 1 4 2 4 1 5 2 5 Follow Graph U1 U2 F3 F4 F5 ALGORITHM STEPS 1 Self-Join Table Join R1.follower = R2.follower where R1.user < R2.user 2 Group By Pairs GROUP BY (user1, user2) COUNT common followers 3 Find Maximum Subquery: MAX(count) from grouped results 4 Filter Results HAVING count = max_count Return qualifying pairs Pair Counts: U1 U2 Cnt 1 2 3 MAX = 3 FINAL RESULT Pairs with Maximum Common Followers U1 U2 3 common F3 F4 F5 Output: (1, 2) OK - Max count = 3 Key Insight: Use SELF-JOIN on follower_id to find users sharing the same follower. Group by user pairs, count common followers, then filter using HAVING clause to keep only pairs matching the maximum count found via a subquery. Constraint user1 < user2 ensures unique ordered pairs. TutorialsPoint - All the Pairs With the Maximum Number of Common Followers | Optimal Solution
Asked in
Facebook 28 Instagram 22 LinkedIn 18
25.4K Views
Medium Frequency
~20 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen