MediumNo. 0578LeetCode Premium
Get Highest Answer Rate Question — LeetCode 578 Python Solution
- Topics
- Database
- Reading time
- 3 min
- Source
- leetcode.com
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
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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0577 | Employee Bonus | Easy |
| 0584 | Find Customer Referee | Easy |
| 0585 | Investments in 2016 | Medium |
| 0570 | Managers with at Least 5 Direct Reports | Medium |
| 0586 | Customer Placing the Largest Number of Orders | Easy |
| 0175 | Combine Two Tables | Easy |
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.