Weekly Power-User Share per Country from Impression Logs
Arrays & HashingAuto-graded · 16 test casesLast updated
Group impression records by country and user over a 7-day window, flag users with 4+ active dates and 3+ surfaces on one date, and report per-country percentages.
Weekly Power-User Share per Country
You are given a list of impression records. Each record is a dictionary with these keys:
| Key | Meaning |
|---|---|
impression_id | Identifier of the impression. |
user_id | The user who received the impression. May be None. |
pin_id | The pin shown. |
surface | Where the impression was shown, for example "home", "search" or "related". |
impression_ts | Timestamp string such as "2025-03-01 10:00:00". |
country_code | Country recorded for the impression. May be None. |
You are also given today, an ISO date string such as "2025-03-04".
Window
The window is the 7 calendar dates made up of today and the 6 dates before it, both ends inclusive. The date of an impression is the date part of impression_ts, which is its first 10 characters (YYYY-MM-DD). Ignore the time of day. Impressions whose date falls outside the window are ignored.
Definitions
Treat each (country_code, user_id) pair as its own entity. A user with impressions in two countries is evaluated separately in each one, using only the impressions recorded in that country.
- A pair is active if it has at least one impression in the window.
- A pair is highly active if both of these hold, using only impressions in the window:
- It has impressions on at least 4 distinct dates.
- On at least one single date, it has impressions on at least 3 distinct surfaces. Surfaces seen on different dates must not be combined.
Records where user_id is None or country_code is None are skipped entirely.
Task
Implement a function that returns one dictionary per country that has at least one active user. Each dictionary has these keys:
country_code: the country.active_users: the number of active users in that country.highly_active_users: how many of those users are highly active.highly_active_pct:highly_active_users / active_users * 100, rounded to two decimal places with halves rounded up (away from zero), returned as afloat.
A country is included even if none of its active users are highly active (its percentage is then 0.0).
Sort the result by highly_active_pct descending, then by country_code ascending.
If no record falls in the window, return an empty list.
Constraints
rowsmay be empty.impression_tsalways begins with a validYYYY-MM-DDdate.todayis a valid ISO date string.- Compute the percentage with exact decimal arithmetic so that rounding is correct (avoid binary-float artifacts).
- Duplicate impressions on the same date, or repeated surfaces on the same date, count only once toward the distinct counts.
Examples
Example 1
Input: power_user_share_by_country([{'impression_id': 1, 'user_id': 10, 'pin_id': 1, 'surface': 'home', 'impression_ts': '2025-03-01 10:00:00', 'country_code': 'US'}, {'impression_id': 2, 'user_id': 10, 'pin_id': 2, 'surface': 'search', 'impression_ts': '2025-03-01 11:00:00', 'country_code': 'US'}, {'impression_id': 3, 'user_id': 10, 'pin_id': 3, 'surface': 'related', 'impression_ts': '2025-03-01 12:00:00', 'country_code': 'US'}, {'impression_id': 4, 'user_id': 10, 'pin_id': 4, 'surface': 'home', 'impression_ts': '2025-03-02 10:00:00', 'country_code': 'US'}, {'impression_id': 5, 'user_id': 10, 'pin_id': 5, 'surface': 'home', 'impression_ts': '2025-03-03 10:00:00', 'country_code': 'US'}, {'impression_id': 6, 'user_id': 10, 'pin_id': 6, 'surface': 'home', 'impression_ts': '2025-03-04 10:00:00', 'country_code': 'US'}, {'impression_id': 7, 'user_id': 11, 'pin_id': 7, 'surface': 'home', 'impression_ts': '2025-03-04 10:00:00', 'country_code': 'US'}], '2025-03-04')
Output: [{'country_code': 'US', 'active_users': 2, 'highly_active_users': 1, 'highly_active_pct': 50}]
Example 2
Input: power_user_share_by_country([], '2025-03-04')
Output: []
Hints
Hint 1
Build two lookups while scanning the rows: the set of active dates for each (country, user), and the set of surfaces for each (country, user, date).
Hint 2
A user meets the surface rule if any one of their dates has a surface set of size 3 or more. Check this per date, never across dates.
Hint 3
Round the percentage with Decimal and ROUND_HALF_UP rather than Python's float round. Then sort with the key (-pct, country_code).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a two-level grouping followed by a rollup.
- Scan the records. Skip any with a missing user or country. Take the date from the first 10 characters of the timestamp and keep it only if it lies between
today - 6 daysandtoday, inclusive. - For each kept record, with key
(country, user):- add the date to that key's set of active dates;
- add the surface to the set stored for
(key, date).
- For each
(country, user)key, count it as active. It is highly active when it has at least 4 distinct dates and at least one of those dates has a surface set of size 3 or more. - Add these results into per-country totals of active and highly active users.
- For each country, compute
highly_active / active * 100withDecimal, quantize to two places usingROUND_HALF_UP, and convert tofloat. - Sort by percentage descending, then country code ascending.
Why it is correct
- Sets remove duplicate dates and duplicate surfaces, so they cannot inflate the distinct counts.
- Surfaces are stored per
(user, date), so surfaces from different days are never merged. This enforces the "same single date" rule. - A date with 3 or more surfaces is necessarily one of the user's active dates, so the two conditions are checked over the same window.
- Keying by
(country, user)evaluates a user independently in each country. - Countries appear in the output as soon as they have one active user, so countries with zero highly active users are still included. Division by zero cannot occur.
DecimalwithROUND_HALF_UPavoids float artifacts such asround(2.675, 2)giving2.67.
Complexity
With n records, time is O(n) for the scan plus O(k log k) to sort k countries. Space is O(n) for the sets in the worst case.
Reference solution
from collections import defaultdict
from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP
from typing import Dict, List
def power_user_share_by_country(records: List[Dict], today: str) -> List[Dict]:
end = date.fromisoformat(today)
start = end - timedelta(days=6)
user_dates = defaultdict(set)
date_surfaces = defaultdict(set)
for row in records:
if row.get("user_id") is None or row.get("country_code") is None:
continue
activity_date = date.fromisoformat(row["impression_ts"][:10])
if start <= activity_date <= end:
key = (row["country_code"], row["user_id"])
user_dates[key].add(activity_date)
date_surfaces[(key, activity_date)].add(row["surface"])
counts = defaultdict(lambda: [0, 0])
for (country, user), dates in user_dates.items():
counts[country][0] += 1
is_highly_active = len(dates) >= 4 and any(
len(date_surfaces[((country, user), d)]) >= 3 for d in dates
)
counts[country][1] += int(is_highly_active)
result = []
for country, (active, highly_active) in counts.items():
pct = (Decimal(highly_active) * 100 / Decimal(active)).quantize(
Decimal("0.01"), rounding=ROUND_HALF_UP
)
result.append({
"country_code": country,
"active_users": active,
"highly_active_users": highly_active,
"highly_active_pct": float(pct),
})
return sorted(result, key=lambda r: (-r["highly_active_pct"], r["country_code"]))