Friend Requests II: Who Has the Most Friends — LeetCode 602 Python Solution

MediumDatabase
Problem
#602
Reading time
2 min

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

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview