Segment Survey Ratings by User Tenure and Region
SQL & DataAuto-graded · 15 test casesLast updated
Filter invalid responses, categorize users by signup tenure, and aggregate satisfaction metrics by region and cohort.
You are given two lists of dictionaries representing user data (users) and survey submissions (surveys).
Each dictionary in users contains:
"user_id"(int): Unique identifier for the account."signup_date"(str): ISO formatted date ("YYYY-MM-DD") when the account was created."country"(str): Country code of the user.
Each dictionary in surveys contains:
"survey_id"(int): Unique identifier for the submission."user_id"(int): Identifier matching a user inusers."survey_date"(str): ISO formatted date ("YYYY-MM-DD") when the survey was taken."satisfaction_score"(int orNone): Rating scale integer, orNoneif unanswered."is_test"(bool):Trueif generated by automated testing,Falsefor valid submissions.
Business Logic & Data Cleaning Rules
-
Filtering:
- Omit any submission where
is_testisTrue. - Omit any submission where
satisfaction_scoreisNone. - Omit any record where
user_iddoes not exist inusers. - Omit invalid entries where
survey_dateoccurred prior tosignup_date(i.e. elapsed days < 0).
- Omit any submission where
-
Cohort Categorization:
"New": The survey was completed within 30 days of registration inclusive ($0 \le \text{survey_date} - \text{signup_date} \le 30$)."Established": The survey was completed strictly more than 30 days after registration ($\text{survey_date} - \text{signup_date} > 30$).
-
Metrics per Group: Group valid records by
countryanduser_cohortand calculate:country(str): Country code.user_cohort(str):"New"or"Established".unique_respondents(int): Number of distinct users who submitted at least one valid survey in this group.total_responses(int): Count of valid survey submissions in this group.avg_satisfaction(float): Mean satisfaction score, rounded to 2 decimal places using half-up rounding (e.g. 3.125 becomes 3.13).
-
Output Ordering: Return a list of dictionaries sorted by
countryin ascending alphabetical order, then byuser_cohortin ascending alphabetical order (note that'Established'comes before'New'). Groups with no valid records must not be included.
Constraints
- $0 \le \text{len(users)} \le 1000$
- $0 \le \text{len(surveys)} \le 5000$
- Dates are guaranteed to be valid
"YYYY-MM-DD"strings.
Examples
Example 1
Input: compare_survey_satisfaction([{'user_id': 101, 'signup_date': '2024-01-01', 'country': 'US'}, {'user_id': 102, 'signup_date': '2024-01-01', 'country': 'US'}, {'user_id': 103, 'signup_date': '2024-02-15', 'country': 'US'}, {'user_id': 104, 'signup_date': '2024-03-01', 'country': 'GB'}], [{'survey_id': 1, 'user_id': 101, 'survey_date': '2024-01-15', 'satisfaction_score': 4, 'is_test': False}, {'survey_id': 2, 'user_id': 101, 'survey_date': '2024-02-20', 'satisfaction_score': 5, 'is_test': False}, {'survey_id': 3, 'user_id': 102, 'survey_date': '2024-02-10', 'satisfaction_score': 3, 'is_test': False}, {'survey_id': 4, 'user_id': 103, 'survey_date': '2024-02-20', 'satisfaction_score': None, 'is_test': False}, {'survey_id': 5, 'user_id': 103, 'survey_date': '2024-02-22', 'satisfaction_score': 2, 'is_test': True}, {'survey_id': 6, 'user_id': 104, 'survey_date': '2024-03-05', 'satisfaction_score': 5, 'is_test': False}])
Output: [{'country': 'GB', 'user_cohort': 'New', 'unique_respondents': 1, 'total_responses': 1, 'avg_satisfaction': 5}, {'country': 'US', 'user_cohort': 'Established', 'unique_respondents': 2, 'total_responses': 2, 'avg_satisfaction': 4}, {'country': 'US', 'user_cohort': 'New', 'unique_respondents': 1, 'total_responses': 1, 'avg_satisfaction': 4}]
Hints
Hint 1
Map users by user_id first for efficient O(1) lookup.
Hint 2
A single user can contribute to both 'New' and 'Established' cohorts if they take multiple surveys over time.
Hint 3
Use Python's decimal module with ROUND_HALF_UP to achieve precise half-up rounding matching standard database numeric types.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires data joining, filtering, conditional classification, and aggregation.
- User Lookup: Create a hash map mapping
user_idto user record for fast $O(1)$ joins. - Filtering: Iterate through each survey and discard records if:
is_testis true.satisfaction_scoreisNone.user_iddoes not match any existing user.survey_dateis earlier thansignup_date.
- Cohort Assignment: Determine the age of the user at the time of the survey:
- $0 \le \text{days} \le 30 \implies \text{"New"}$
- $\text{days} > 30 \implies \text{"Established"}$
- Aggregation: Aggregate score sums, response counts, and unique set of user IDs using standard grouping keys
(country, cohort). - Rounding & Ordering: Sort output groups lexicographically by
(country, cohort). Note that string sorting automatically places"Established"before"New". UseDecimal.quantizewithROUND_HALF_UPto match exact financial/database rounding behavior.
Complexity Analysis
- Time Complexity: $O(U + S + G \log G)$, where $U$ is the number of users, $S$ is the number of surveys, and $G$ is the number of formed groups. Processing users takes $O(U)$, iterating surveys takes $O(S)$, and sorting final groups takes $O(G \log G)$ where $G \le 2 \times \text{countries}$.
- Space Complexity: $O(U + S)$ to store the user lookup map and unique user sets for each aggregate bucket.