Calculate Engaged User Percentage by Region
SQL & DataAuto-graded · 14 test casesLast updated
Classify users as engaged based on activity frequency and device diversity, then compute the engaged-user rate per region.
You have a list of playback events from a streaming service. Each event is a dictionary with these fields:
user_id: identifier of the usertrack_id: identifier of the track playeddevice: the device type used ("app","web", or"car")event_ts: timestamp of the event in ISO formatregion_code: the region where the user was located
You need to analyze user engagement within a 7-day window that includes a given today date plus the 6 preceding days (7 calendar days total, determined by the date portion of event_ts).
Within each region, a user is considered active if they have at least one playback event during the window. A user is considered engaged if they meet both of these criteria during the window:
- They played content on at least 4 distinct calendar days
- On at least one of those days, they used 3 or more distinct device types
Note that the device diversity requirement must be satisfied within a single day—using three different devices across three separate days does not count.
A user may appear in multiple regions if they were active in different regions during the window. Each user-region combination should be evaluated independently.
Return a list of dictionaries, one per region that has at least one active user, containing:
region_code: the region identifieractive_users: count of active users in that regionpower_users: count of engaged users in that regionpower_user_pct: percentage of active users who are engaged (power_users / active_users * 100), rounded to 2 decimal places
Sort the results by power_user_pct descending, then by region_code ascending.
Constraints
- 1 ≤ number of events ≤ 100,000
todayis a valid ISO date string (YYYY-MM-DD)- All
event_tsvalues are valid ISO datetime strings - Each event has all required fields
- Device types are limited to
"app","web", and"car" - Region codes are non-empty strings
Examples
Example 1
Input: calculate_engaged_user_rate([{'user_id': 'u1', 'track_id': 'a', 'device': 'app', 'event_ts': '2026-10-16T10:00:00', 'region_code': 'US'}, {'user_id': 'u1', 'track_id': 'b', 'device': 'app', 'event_ts': '2026-10-17T10:00:00', 'region_code': 'US'}, {'user_id': 'u1', 'track_id': 'c', 'device': 'web', 'event_ts': '2026-10-17T11:00:00', 'region_code': 'US'}, {'user_id': 'u1', 'track_id': 'd', 'device': 'app', 'event_ts': '2026-10-18T10:00:00', 'region_code': 'US'}, {'user_id': 'u1', 'track_id': 'e', 'device': 'web', 'event_ts': '2026-10-18T11:00:00', 'region_code': 'US'}, {'user_id': 'u1', 'track_id': 'f', 'device': 'car', 'event_ts': '2026-10-18T12:00:00', 'region_code': 'US'}, {'user_id': 'u1', 'track_id': 'g', 'device': 'app', 'event_ts': '2026-10-19T10:00:00', 'region_code': 'US'}, {'user_id': 'u2', 'track_id': 'h', 'device': 'app', 'event_ts': '2026-10-20T10:00:00', 'region_code': 'US'}, {'user_id': 'u3', 'track_id': 'i', 'device': 'app', 'event_ts': '2026-10-15T10:00:00', 'region_code': 'CA'}, {'user_id': 'u3', 'track_id': 'j', 'device': 'app', 'event_ts': '2026-10-16T10:00:00', 'region_code': 'CA'}, {'user_id': 'u3', 'track_id': 'k', 'device': 'app', 'event_ts': '2026-10-17T10:00:00', 'region_code': 'CA'}, {'user_id': 'u3', 'track_id': 'l', 'device': 'app', 'event_ts': '2026-10-18T10:00:00', 'region_code': 'CA'}, {'user_id': 'u3', 'track_id': 'm', 'device': 'web', 'event_ts': '2026-10-18T11:00:00', 'region_code': 'CA'}, {'user_id': 'u3', 'track_id': 'n', 'device': 'car', 'event_ts': '2026-10-18T12:00:00', 'region_code': 'CA'}, {'user_id': 'u4', 'track_id': 'o', 'device': 'app', 'event_ts': '2026-10-20T10:00:00', 'region_code': 'CA'}], '2026-10-20')
Output: [{'region_code': 'CA', 'active_users': 2, 'power_users': 1, 'power_user_pct': 50}, {'region_code': 'US', 'active_users': 2, 'power_users': 1, 'power_user_pct': 50}]
Hints
Hint 1
Group events first by user, region, and date to count distinct devices used each day
Hint 2
Track both the number of distinct active days per user and the maximum device count achieved on any single day
Hint 3
A user qualifies as engaged only when both thresholds are met: 4+ days AND 3+ devices on at least one day
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution processes events in three stages:
-
Filter and aggregate by user-day: First, filter events to the 7-day window. Then group events by region, user, and date to count how many distinct devices each user used on each day.
-
Aggregate by user: For each user in each region, determine (a) how many distinct days they were active, and (b) whether they ever used 3+ distinct devices on a single day. A user qualifies as engaged if they meet both criteria: 4+ active days AND at least one day with 3+ devices.
-
Aggregate by region: Count total active users and engaged users per region, compute the percentage, and sort results.
Why it works
The key insight is that the device-diversity requirement operates at the daily granularity—we need to check each individual day's device count, not aggregate devices across all days. By first collapsing events to user-day-device tuples, we can accurately count devices per day and track whether any day reaches the 3-device threshold.
The two-level aggregation (user-day, then user-region) ensures we correctly evaluate both conditions independently before combining them.
Complexity
- Time: O(n + m log m) where n is the number of events and m is the number of regions. We iterate through events once, then sort regions.
- Space: O(n) to store the intermediate aggregations (user-day combinations and per-region user sets).
Solution
from collections import defaultdict
from datetime import date, datetime, timedelta
from decimal import Decimal, ROUND_HALF_UP
from typing import Dict, List
def calculate_engaged_user_rate(play_events: List[Dict], today: str) -> List[Dict]:
end_date = date.fromisoformat(today)
start_date = end_date - timedelta(days=6)
active_users = defaultdict(set)
devices_by_user_day = defaultdict(set)
for event in play_events:
event_date = datetime.fromisoformat(event["event_ts"]).date()
if start_date <= event_date <= end_date:
region = event["region_code"]
user = event["user_id"]
active_users[region].add(user)
devices_by_user_day[(region, user, event_date)].add(event["device"])
days_by_user = defaultdict(set)
diverse_day_users = set()
for (region, user, event_date), devices in devices_by_user_day.items():
days_by_user[(region, user)].add(event_date)
if len(devices) >= 3:
diverse_day_users.add((region, user))
result = []
for region, users in active_users.items():
active_count = len(users)
power_count = sum(
1 for user in users
if len(days_by_user[(region, user)]) >= 4
and (region, user) in diverse_day_users
)
percentage = (Decimal(power_count) * Decimal(100) / Decimal(active_count)).quantize(
Decimal("0.01"), rounding=ROUND_HALF_UP
)
result.append({
"region_code": region,
"active_users": active_count,
"power_users": power_count,
"power_user_pct": float(percentage),
})
result.sort(key=lambda row: (-row["power_user_pct"], row["region_code"]))
return result