Popularity Percentage - Problem

Given a Friends table containing friendship relationships, calculate the popularity percentage for each user on Meta/Facebook.

The popularity percentage is defined as:

  • Total number of friends the user has
  • Divided by total number of users on the platform
  • Multiplied by 100 and rounded to 2 decimal places

Return results ordered by user1 in ascending order.

Note: Friendship is bidirectional - if user A is friends with user B, then user B is also friends with user A.

Table Schema

Friends
Column Name Type Description
user1 PK int First user in friendship pair
user2 PK int Second user in friendship pair
Primary Key: (user1, user2)
Note: Each row represents a bidirectional friendship between user1 and user2

Input & Output

Example 1 — Basic Friendship Network
Input Table:
user1 user2
1 2
1 3
2 3
Output:
user1 percentage
1 66.67
2 66.67
3 66.67
💡 Note:

There are 3 total users (1, 2, 3). Each user has 2 friends:

  • User 1 is friends with users 2 and 3
  • User 2 is friends with users 1 and 3
  • User 3 is friends with users 1 and 2

Popularity percentage = (2 friends / 3 total users) × 100 = 66.67%

Example 2 — Unequal Popularity
Input Table:
user1 user2
1 2
1 3
1 4
Output:
user1 percentage
1 75
2 25
3 25
4 25
💡 Note:

There are 4 total users. User 1 has 3 friends (75.00%), while users 2, 3, and 4 each have only 1 friend (25.00%).

Constraints

  • 1 ≤ user1, user2 ≤ 1000
  • user1 ≠ user2
  • All friendships are unique pairs
  • Friendship is bidirectional

Visualization

Tap to expand
Popularity Percentage Problem OverviewFriends Tableuser1user2121323UNION ALLBidirectionalAll User-Friend Pairsuser_idfriend_id1→2,3(2 friends)2→1,3(2 friends)3→1,2(2 friends)GROUP BYCalculate %Popularity Resultuser1percentage166.67266.67366.67Formula: (Friend Count / Total Users) × 100Each user: (2 friends / 3 total users) × 100 = 66.67%
Understanding the Visualization
1
Input
Friendship pairs table
2
Union
Create bidirectional relationships
3
Group & Calculate
Count friends and compute percentages
Key Takeaway
🎯 Key Insight: Use UNION ALL to handle bidirectional relationships in social network data
Asked in
Meta 28 Google 15 Amazon 12
28.5K Views
Medium Frequency
~18 min Avg. Time
890 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