Get Highest Answer Rate Question — LeetCode 578 Python Solution

MediumLeetCode PremiumDatabase
Problem
#578
Reading time
3 min

The problem

Find the question with the highest answer rate, where a question's answer rate is the number of times it was answered divided by the number of times it was shown; when several questions tie, report the smallest question_id. SurveyLog has id (int), action (one of show, answer and skip), question_id (int), answer_id (int, filled in only when the action is answer), q_num (int) and timestamp (int), and the table may contain duplicate rows. Return a single column named survey_log.

Example

Input
SurveyLog(id, action, question_id, answer_id, q_num, timestamp) = (1, 'show', 101, null, 1, 1000), (1, 'answer', 101, 5001, 1, 1005), (2, 'show', 101, null, 1, 1100), (2, 'skip', 101, null, 1, 1105), (3, 'show', 102, null, 2, 1200), (3, 'answer', 102, 5002, 2, 1210)
Output
survey_log = 102
Explanation
Question 101 is answered 1 of the 2 times it is shown (0.5) while question 102 is answered every time it is shown (1.0).

Python solution

Python
import pandas as pd

def highest_answer_rate_question(survey_log: pd.DataFrame) -> pd.DataFrame:
    counts = survey_log.groupby(['question_id', 'action']).size().unstack(fill_value=0)
    show = counts.get('show', pd.Series(dtype=int))
    answer = counts.get('answer', pd.Series(dtype=int))
    rate = answer / show.replace(0, pd.NA)
    rate = rate.fillna(0)
    max_rate = rate.max()
    best_q = rate[rate == max_rate].index.min()
    return pd.DataFrame({'survey_log': [int(best_q)]})

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 578. Get Highest Answer Rate Question?
LeetCode 578. Get Highest Answer Rate Question is rated Medium on LeetCode.
What topics does LeetCode 578. Get Highest Answer Rate Question cover?
LeetCode 578. Get Highest Answer Rate Question is tagged Database on LeetCode.
Is LeetCode 578. Get Highest Answer Rate Question a premium problem?
Yes. LeetCode 578. Get Highest Answer Rate Question 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