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 - SQL Solution INPUT: Friends Table user1 user2 1 2 1 3 2 3 2 4 3 4 4 5 Friendship Graph: 1 2 3 4 5 ALGORITHM STEPS 1 UNION All Friendships Combine user1, user2 with user2, user1 (bidirectional) 2 Count Friends Per User GROUP BY user, COUNT(*) friends for each person 3 Get Total User Count COUNT(DISTINCT user) from union result 4 Calculate Percentage (friends / total) * 100 ROUND to 2 decimals SELECT user1, ROUND(COUNT(*)*100.0 / total_users, 2) AS popularity_pct ORDER BY user1; FINAL RESULT user1 popularity% 1 40.00 2 60.00 3 60.00 4 60.00 5 20.00 Example Calculation: User 1: 2 friends / 5 users = 0.4 * 100 = 40.00% User 2: 3 friends / 5 users = 0.6 * 100 = 60.00% OK - Sorted by user1 Key Insight: Friendships are bidirectional - if A is friends with B, then B is also friends with A. Use UNION to combine (user1, user2) and (user2, user1) to count all friends for each user. Total users = COUNT(DISTINCT user) from the combined set, not just from one column. TutorialsPoint - Popularity Percentage | Optimal Solution
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