Survey Click-Through and Score Averages from Impression Logs
Arrays & HashingAuto-graded · 17 test casesLast updated
Group survey impression records to compute a click rate, a plain score average, and an average of each user's earliest score per survey, with careful handling of missing values.
Survey Feedback Summary
A travel app shows surveys to users. Every time a survey is displayed, one record is logged. If the user engages with it, the record also carries a click time and possibly a rating.
You are given records, a list of dictionaries, one per displayed survey. Each dictionary has these keys:
user_id: integer identifying the user.survey_id: integer identifying the survey.impression_ts: string inYYYY-MM-DD HH:MM:SSformat, when the survey was shown.click_ts: string in the same format, orNoneif the user did not click.score: integer rating, orNoneif no rating was given.
Because the timestamps are zero-padded ISO-style strings, comparing them as strings gives chronological order.
Return a dictionary with exactly three keys:
"response_rate": the number of records whoseclick_tsis notNone, divided by the total number of records."average_score_all": the mean of everyscorethat is notNone."average_first_score": the mean of one score per(user_id, survey_id)pair, as defined below.
Choosing the first score of a pair
Consider only the records of a pair that have a non-None score. The pair's first score is the score of the record that comes earliest under this ordering:
- Smaller
click_tsfirst, where a missingclick_ts(None) counts as smaller than any real timestamp. - If still tied, smaller
impression_tsfirst. - If still tied, the record that appears earlier in
records.
Pairs with no scored record contribute nothing. average_first_score is the mean of the selected scores, one per pair that has at least one score.
Empty cases
- If
recordsis empty,response_rateisNone. - If there are no non-
Nonescores at all, bothaverage_score_allandaverage_first_scoreareNone.
Averages are ordinary floating-point means, not floored.
Constraints
0 <= len(records) <= 10^5user_idandsurvey_idare always present and are integers.score, when present, is an integer.impression_tsis always present;click_tsandscoremay beNone.- Aim for roughly O(n log n) time or better.
Examples
Example 1
Input: summarize_survey_feedback([{'user_id': 101, 'survey_id': 555, 'impression_ts': '2023-09-01 10:00:00', 'click_ts': '2023-09-01 10:05:12', 'score': 4}, {'user_id': 102, 'survey_id': 555, 'impression_ts': '2023-09-01 10:02:34', 'click_ts': None, 'score': None}, {'user_id': 101, 'survey_id': 556, 'impression_ts': '2023-09-02 09:15:20', 'click_ts': '2023-09-02 09:16:00', 'score': 5}, {'user_id': 103, 'survey_id': 555, 'impression_ts': '2023-09-01 10:10:00', 'click_ts': None, 'score': None}, {'user_id': 104, 'survey_id': 557, 'impression_ts': '2023-09-03 11:00:00', 'click_ts': '2023-09-03 11:02:45', 'score': 3}])
Output: {'response_rate': 0.6, 'average_score_all': 4, 'average_first_score': 4}
Example 2
Input: summarize_survey_feedback([{'user_id': 1, 'survey_id': 10, 'impression_ts': '2024-01-01 09:00:00', 'click_ts': '2024-01-01 09:01:00', 'score': 5}, {'user_id': 1, 'survey_id': 10, 'impression_ts': '2024-01-02 09:00:00', 'click_ts': '2024-01-02 09:01:00', 'score': 2}, {'user_id': 2, 'survey_id': 10, 'impression_ts': '2024-01-01 10:00:00', 'click_ts': '2024-01-01 10:02:00', 'score': 4}])
Output: {'response_rate': 1, 'average_score_all': 3.6666666666666665, 'average_first_score': 4.5}
Example 3
Input: summarize_survey_feedback([{'user_id': 7, 'survey_id': 20, 'impression_ts': '2024-02-01 12:00:00', 'click_ts': None, 'score': None}])
Output: {'response_rate': 0, 'average_score_all': None, 'average_first_score': None}
Example 4
Input: summarize_survey_feedback([{'user_id': 3, 'survey_id': 30, 'impression_ts': '2024-03-01 08:00:00', 'click_ts': '2024-03-01 08:01:00', 'score': 1}, {'user_id': 3, 'survey_id': 31, 'impression_ts': '2024-03-01 08:02:00', 'click_ts': '2024-03-01 08:03:00', 'score': 5}])
Output: {'response_rate': 1, 'average_score_all': 3, 'average_first_score': 3}
Hints
Hint 1
Each of the three numbers has its own denominator: all records for the rate, all non-missing scores for the first average, and scored pairs for the second.
Hint 2
Pairs are keyed by (user_id, survey_id). Only scored records compete to be the pair's first score, so skip unscored ones before picking.
Hint 3
Sort the records with a key of (user_id, survey_id, click_ts or '', impression_ts or '', original index), then keep the first scored record you see for each pair. An empty string sorts before any timestamp.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The three outputs are independent aggregates, each with its own denominator.
- Response rate. Every record is one impression, and a click exists exactly when
click_tsis notNone. Count the clicks and divide by the number of records. For an empty list, returnNone. - Average of all scores. Collect every non-
Nonescore and take the mean. If the collection is empty, returnNone. Unrated records are skipped, so they do not pull the average toward zero. - Average of first scores per pair.
- Sort the records (keeping each record's original index) by
(user_id, survey_id, click_ts, impression_ts, index). A missingclick_tsorimpression_tsis replaced by the empty string, which sorts before every real timestamp. This implements the "missing click first" rule. - Walk the sorted list. For each record that has a score, store it in a dictionary keyed by
(user_id, survey_id)only if that pair has no stored score yet. - Average the dictionary's values, or return
Noneif it is empty.
- Sort the records (keeping each record's original index) by
Why it is correct
Sorting places all records of a pair next to each other, in exactly the tie-break order the statement defines. Skipping unscored records during the walk means the first scored record encountered for a pair is the earliest scored record under that ordering. That record is the pair's first score. The dictionary guard guarantees one score per pair, and pairs with no scored record never enter it.
The empty-input and no-score cases are handled by explicit checks before each division, so no division by zero occurs.
Which average is the better headline metric
The first-score average is usually preferable. A user who resubmits many times would otherwise weigh much more than everyone else in the plain average, and repeat responders tend to be extreme. Early answers are also less affected by re-prompting. The plain average remains useful as a diagnostic. A big gap between the two signals that repeat submissions exist.
Complexity
- Time: O(n log n), dominated by the sort. The two other aggregates are O(n).
- Space: O(n) for the sorted copy and the dictionary of per-pair first scores.
Reference solution
from typing import Dict, List, Optional
def summarize_survey_feedback(records: List[Dict]) -> Dict[str, Optional[float]]:
total = len(records)
clicks = sum(1 for r in records if r.get("click_ts") is not None)
response_rate = clicks / total if total else None
all_scores = [r["score"] for r in records if r.get("score") is not None]
average_score_all = sum(all_scores) / len(all_scores) if all_scores else None
ordered = sorted(
enumerate(records),
key=lambda item: (
item[1].get("user_id"),
item[1].get("survey_id"),
item[1].get("click_ts") or "",
item[1].get("impression_ts") or "",
item[0],
),
)
first_by_pair = {}
for _, r in ordered:
score = r.get("score")
if score is None:
continue
pair = (r.get("user_id"), r.get("survey_id"))
if pair not in first_by_pair:
first_by_pair[pair] = score
firsts = list(first_by_pair.values())
average_first_score = sum(firsts) / len(firsts) if firsts else None
return {
"response_rate": response_rate,
"average_score_all": average_score_all,
"average_first_score": average_first_score,
}