Friend Requests II: Who Has the Most Friends — LeetCode 602 Python Solution
MediumDatabase
- Problem
- #602
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Every accepted request makes both people friends. Report the id of the person with the most friends together with that number; the test data guarantees only one person holds the record. The RequestAccepted table has one row per accepted request: requester_id (int), accepter_id (int) and accept_date (date), with the pair (requester_id, accepter_id) as the primary key.
Example
RequestAccepted table: | requester_id | accepter_id | accept_date | | ------------ | ----------- | ----------- | | 11 | 21 | 2024-01-04 | | 11 | 31 | 2024-01-06 | | 21 | 31 | 2024-01-09 | | 31 | 41 | 2024-01-11 | Result: | id | num | | -- | --- | | 31 | 3 | User 31 appears in three accepted requests and so has three friends, ahead of 11 and 21 with two each and 41 with one.
Python solution
Python
import pandas as pd
def most_friends(request_accepted: pd.DataFrame) -> pd.DataFrame:
ids = pd.concat([request_accepted['requester_id'], request_accepted['accepter_id']], ignore_index=True)
counts = ids.value_counts()
max_cnt = counts.max()
person = counts[counts == max_cnt].index.min()
return pd.DataFrame({'id': [int(person)], 'num': [int(max_cnt)]})Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 602. Friend Requests II: Who Has the Most Friends?
- LeetCode 602. Friend Requests II: Who Has the Most Friends is rated Medium on LeetCode.
- What topics does LeetCode 602. Friend Requests II: Who Has the Most Friends cover?
- LeetCode 602. Friend Requests II: Who Has the Most Friends is tagged Database on LeetCode.