Find Bottom Three Active Regions by Unique User Count
SQL & DataAuto-graded · 17 test casesLast updated
Aggregate user log data to calculate distinct active users per country in 2023, then return the 3 least active countries.
Given a list of user profiles users and a list of user activity events events, identify up to 3 countries with the fewest unique active users throughout the calendar year 2023.
Each item in users is a dictionary containing:
"user_id"(int): Unique identifier for the user."country"(str): The region or country associated with the user.
Each item in events is a dictionary containing:
"event_id"(int): Unique identifier for the activity."user_id"(int): Reference to the user who performed the activity."event_date"(strordatetime.date): Date when the activity took place (formatted as"YYYY-MM-DD"if string).
Requirements:
- An active user is defined as any user with at least one event occurring between
2023-01-01and2023-12-31(inclusive). - Count the number of distinct active users for each country. Do not count multiple events by the same user multiple times.
- Exclude countries with zero active users in 2023.
- Ignore any event whose
user_iddoes not exist inusers. - Return a list of dictionaries, where each entry has keys
"country"and"unique_users". - Sort the final output by
"unique_users"in ascending order. If two countries have the same count, break ties by sorting the"country"name alphabetically (lexicographically ascending). - Return at most the top 3 countries from this sorted list.
Constraints
0 <= len(users) <= 10^40 <= len(events) <= 5 * 10^4event_dateis guaranteed to be a string in"YYYY-MM-DD"format or adatetime.dateobject.
Examples
Example 1
Input: find_least_active_countries([{'user_id': 1, 'country': 'USA'}, {'user_id': 2, 'country': 'USA'}, {'user_id': 3, 'country': 'Canada'}, {'user_id': 4, 'country': 'Mexico'}], [{'event_id': 101, 'user_id': 1, 'event_date': '2023-01-01'}, {'event_id': 102, 'user_id': 2, 'event_date': '2023-02-01'}, {'event_id': 103, 'user_id': 3, 'event_date': '2023-03-01'}])
Output: [{'country': 'Canada', 'unique_users': 1}, {'country': 'USA', 'unique_users': 2}]
Hints
Hint 1
Create a map from user_id to country first to enable O(1) user profile lookups.
Hint 2
Filter out any events occurring outside of 2023 (or involving unknown user IDs), and maintain a set of user IDs per country to ensure uniqueness.
Hint 3
Convert sets to user counts, filter for non-zero counts, and sort using a tuple key (unique_users, country) before slicing the first 3 elements.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires joining user details with event records, filtering by a date range, counting distinct users per country, and identifying the bottom 3 performers.
- User Mapping: Construct a hash map mapping each
user_idto its correspondingcountry. This allows fast lookups during event processing. - Event Processing & Filtering:
- Iterate through each event in
events. - Ensure the date representation is uniform. Convert
datetime.dateinstances to standard ISO format strings (YYYY-MM-DD) if needed. - Check if the event date falls within the 2023 range (
2023-01-01to2023-12-31). - If valid and the user exists in our map, add the
user_idinto a Pythonsetassigned to that country. Using sets handles distinct user deduplication automatically.
- Iterate through each event in
- Aggregation & Sorting:
- Transform the dictionary of sets into a list of dictionaries with keys
"country"and"unique_users". - Sort the list using a tuple key:
(unique_users, country). This sorts counts in ascending order while breaking ties alphabetically by country name. - Take the first 3 elements of the sorted list.
- Transform the dictionary of sets into a list of dictionaries with keys
Complexity
- Time Complexity: $\mathcal{O}(U + E + C \log C)$, where $U$ is the number of users, $E$ is the number of events, and $C$ is the number of active countries in 2023. Mapping users takes $\mathcal{O}(U)$, processing events takes $\mathcal{O}(E)$, and sorting the aggregated country counts takes $\mathcal{O}(C \log C)$.
- Space Complexity: $\mathcal{O}(U + C)$ auxiliary space to store the user-to-country mapping and per-country unique user sets.
Reference Solution
from typing import List, Dict
from datetime import date
def find_least_active_countries(users: List[Dict], events: List[Dict]) -> List[Dict]:
user_country = {user['user_id']: user['country'] for user in users}
active_users = {}
for event in events:
event_date = event['event_date']
if isinstance(event_date, date):
event_date = event_date.isoformat()
if '2023-01-01' <= event_date <= '2023-12-31':
user_id = event['user_id']
if user_id in user_country:
country = user_country[user_id]
active_users.setdefault(country, set()).add(user_id)
result = [
{'country': country, 'unique_users': len(user_ids)}
for country, user_ids in active_users.items()
if user_ids
]
result.sort(key=lambda row: (row['unique_users'], row['country']))
return result[:3]