Friend Requests II: Who Has the Most Friends - Problem

You are given a table RequestAccepted that tracks accepted friend requests between users.

Table: RequestAccepted

Column NameType
requester_idint
accepter_idint
accept_datedate

The primary key is (requester_id, accepter_id). This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted.

Task: Write a SQL solution to find the person who has the most friends and return their ID along with the total number of friends.

The test cases guarantee that only one person has the maximum number of friends.

Table Schema

RequestAccepted
Column Name Type Description
requester_id PK int ID of user who sent the friend request
accepter_id PK int ID of user who accepted the friend request
accept_date date Date when the request was accepted
Primary Key: (requester_id, accepter_id)
Note: Each row represents an accepted friend request. When a request is accepted, both users become friends with each other.

Input & Output

Example 1 — Basic Friend Network
Input Table:
requester_id accepter_id accept_date
1 2 2016-06-03
1 3 2016-06-08
2 3 2016-06-08
3 4 2016-06-09
Output:
id num
3 3
💡 Note:

User 3 has the most friends (3 total). User 3 appears as: accepter when user 1 sent request, accepter when user 2 sent request, and requester when sending to user 4. This gives 3 total friend connections.

Example 2 — Tie Broken by Single Connection
Input Table:
requester_id accepter_id accept_date
1 2 2016-06-03
3 4 2016-06-08
Output:
id num
1 1
💡 Note:

All users have exactly 1 friend each. The query returns user 1 with 1 friend (user 2). Each friendship creates 2 entries in our UNION result, so each person gets counted once.

Constraints

  • 1 ≤ requester_id, accepter_id ≤ 10000
  • requester_id ≠ accepter_id
  • All friend requests in the table are accepted
  • Test cases guarantee exactly one person has the maximum friends

Visualization

Tap to expand
Friend Requests II: Finding Most Popular UserFriend Network1234User 3 has 3 connectionsSQL QueryUNION + GROUP BYQuery Steps1. UNION ALL user IDs2. GROUP BY user_id3. COUNT(*) friends4. ORDER BY count DESCResultidnum33
Understanding the Visualization
1
Input Analysis
Each row shows one accepted friendship
2
UNION Strategy
Combine requesters and accepters into single user list
3
Count Friends
GROUP BY to count total friendships per user
Key Takeaway
🎯 Key Insight: Use UNION ALL to treat friendships as bidirectional relationships, then count occurrences
Asked in
Facebook 25 LinkedIn 18 Twitter 12
34.5K Views
High Frequency
~12 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