Friend Requests I: Overall Acceptance Rate — LeetCode 597 Python Solution

EasyLeetCode PremiumDatabase
Problem
#597
Reading time
2 min

The problem

Report the overall acceptance rate of friend requests, rounded to two decimals: the number of distinct accepted requests divided by the number of distinct requests sent. A repeated row counts once, and the rate is 0.00 when no request was ever sent. The FriendRequest table holds sender_id (int), send_to_id (int) and request_date (date) and may contain duplicate rows. The RequestAccepted table holds requester_id (int), accepter_id (int) and accept_date (date) and may also contain duplicate rows.

Example

FriendRequest table:

| sender_id | send_to_id | request_date |
| --------- | ---------- | ------------ |
| 1         | 2          | 2024-06-01   |
| 1         | 3          | 2024-06-01   |
| 1         | 3          | 2024-06-01   |
| 2         | 3          | 2024-06-02   |

RequestAccepted table:

| requester_id | accepter_id | accept_date |
| ------------ | ----------- | ----------- |
| 1            | 2           | 2024-06-03  |
| 1            | 3           | 2024-06-03  |

Result:

| accept_rate |
| ----------- |
| 0.67        |

The repeated request from 1 to 3 counts once, leaving three distinct requests and two distinct acceptances, and 2 divided by 3 rounds to 0.67.

Python solution

Python
import pandas as pd

def acceptance_rate(friend_request: pd.DataFrame, request_accepted: pd.DataFrame) -> pd.DataFrame:
    req = friend_request[['sender_id', 'send_to_id']].drop_duplicates()
    acc = request_accepted[['requester_id', 'accepter_id']].drop_duplicates()
    req_count = len(req)
    acc_count = len(acc)
    rate = round(acc_count / req_count, 2) if req_count > 0 else 0
    return pd.DataFrame({'accept_rate': [rate]})

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 597. Friend Requests I: Overall Acceptance Rate?
LeetCode 597. Friend Requests I: Overall Acceptance Rate is rated Easy on LeetCode.
What topics does LeetCode 597. Friend Requests I: Overall Acceptance Rate cover?
LeetCode 597. Friend Requests I: Overall Acceptance Rate is tagged Database on LeetCode.
Is LeetCode 597. Friend Requests I: Overall Acceptance Rate a premium problem?
Yes. LeetCode 597. Friend Requests I: Overall Acceptance Rate is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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