Problem
Table: SurveyLog
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| action | ENUM |
| question_id | int |
| answer_id | int |
| q_num | int |
| timestamp | int |
+-------------+------+
This table may contain duplicate rows.
action is an ENUM (category) of the type: "show", "answer", or "skip".
Each row of this table indicates the user with ID = id has taken an action with the question question_id at time timestamp.
If the action taken by the user is "answer", answer_id will contain the id of that answer, otherwise, it will be null.
q_num is the numeral order of the question in the current session.
The answer rate for a question is the number of times a user answered the question by the number of times a user showed the question.
Write a solution to report the question that has the highest answer rate.
If multiple questions have the same maximum answer rate , report the question with the smallest question_id
.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – Aggregation and Division for Answer Rate
Intuition
To find the question with the highest answer rate, we need to count the number of times each question was shown and answered, then compute the answer rate as answers/shows. The question with the highest rate is the answer.
Approach
- For each question, count the number of ‘show’ actions and ‘answer’ actions.
- Compute the answer rate for each question as answers/shows.
- Return the question_id with the highest answer rate. If there are ties, return the smallest question_id.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of rows in SurveyLog, since each row is processed once. - 🧺 Space complexity:
O(m)
, wherem
is the number of unique questions, for storing counts and rates.