KatInterview

Find Bottom Three Active Regions by Unique User Count

SQL & DataAuto-graded · 17 test cases
MediumAuto-gradedSQL & Dataarrayshash-tablesorting

Last 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" (str or datetime.date): Date when the activity took place (formatted as "YYYY-MM-DD" if string).

Requirements:

  1. An active user is defined as any user with at least one event occurring between 2023-01-01 and 2023-12-31 (inclusive).
  2. Count the number of distinct active users for each country. Do not count multiple events by the same user multiple times.
  3. Exclude countries with zero active users in 2023.
  4. Ignore any event whose user_id does not exist in users.
  5. Return a list of dictionaries, where each entry has keys "country" and "unique_users".
  6. 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).
  7. Return at most the top 3 countries from this sorted list.

Constraints

  • 0 <= len(users) <= 10^4
  • 0 <= len(events) <= 5 * 10^4
  • event_date is guaranteed to be a string in "YYYY-MM-DD" format or a datetime.date object.

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.