The Friend Requests II interview question gives you a single table RequestAccepted containing requester_id and accepter_id. You need to write a SQL query to find the person who has the most friends and the total number of friends they have. A person's friend count is the sum of requests they have accepted PLUS the requests they have sent that were accepted.
Companies like Meta, Amazon, and Bloomberg ask this Database interview pattern to test your ability to normalize data. The friendship relationship is bidirectional, but the data is stored directionally (sender vs. receiver). It evaluates whether you can use a UNION ALL to combine columns into a single unified list before performing aggregations.
The solution uses a UNION ALL and Aggregation pattern.
requester_id as user_id and then UNION ALL with a selection of accepter_id as user_id. This essentially lists every instance of a user participating in a friendship.GROUP BY user_id on this derived table and COUNT(*) to get the total number of friends for each user.ORDER BY count DESC and LIMIT 1 to find the user with the maximum friends.Accepted Table: 1 -> 2 1 -> 3 2 -> 3
[1, 1, 2][2, 3, 3][1, 1, 2, 2, 3, 3]UNION removes duplicates. If user A is friends with B and C, they will appear twice in the unified list. UNION would reduce this to 1, ruining the count.LIMIT 1 assumes only one person has the maximum. If the problem asks for all people tied for the maximum, you need a subquery or window function like RANK().When data represents a symmetric relationship (like a graph edge) but is stored in two columns (source, destination), UNION ALL is the standard technique to "flatten" the data so you can group by the entity regardless of its role in the relationship.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Confirmation Rate | Medium | Solve | |
| Product Sales Analysis III | Medium | Solve | |
| Rank Scores | Medium | Solve | |
| Restaurant Growth | Medium | Solve | |
| Product Price at a Given Date | Medium | Solve |