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
Finding Pairs with Maximum Common FollowersInput: Relationsuser_idfollower_id13231424Self-JoinCount CommonAnalysisPair (1,2):Common: 3,4Count: 2 (MAX)Outputuser1_iduser2_id12Step 1: Self-join Relations on follower_idStep 2: Group by user pairs and count common followersStep 3: Find maximum count and return matching pairs
Understanding the Visualization
1
Input
Relations table with user-follower pairs
2
Self-Join
Join on follower_id to find common followers
3
Output
Pairs with maximum common follower count
Key Takeaway
🎯 Key Insight: Self-join tables on common attributes to find relationships between different entities
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