Friend Requests II: Who Has the Most Friends

medium database sql

Problem

RequestAccepted(requester_id, accepter_id, accept_date). Return the user id with the most friends and that count.

Inputr=[(1,2,'a'),(1,3,'b'),(2,3,'c'),(3,4,'d')]
Output(3, 3)
User 3 is connected to 1, 2, 4 — three friends.

SELECT id, COUNT(*) AS num
FROM (SELECT requester_id AS id FROM RequestAccepted
      UNION ALL SELECT accepter_id FROM RequestAccepted) t
GROUP BY id
ORDER BY num DESC
LIMIT 1;
Time: O(n) Space: O(n)