Daily and Rolling Active User Counts with Zero-Fill
Arrays & HashingAuto-graded · 14 test casesLast updated
Tests building a complete calendar spine, counting distinct daily users, and maintaining a 30-day rolling active-user window.
You are given a date range and a list of login event records. Each record is a dictionary with two keys:
user_id(int): the identifier of the person who logged in.login_ts(str): an ISO-8601 timestamp (e.g."2023-01-03T09:00:00Z"). The calendar day is determined by the date portion of this timestamp.
Define two metrics for every calendar day d in the inclusive range [start_date, end_date]:
- DAU(d) — the number of distinct
user_idvalues whose login timestamp falls on calendar dayd. If a user logs in multiple times on the same day (even from different browsers), they are counted once. - MAU_l30d(d) — the number of distinct
user_idvalues who logged in at any point during the 30-day window[d − 29 days, d], inclusive of both endpoints. A user active on several days within the window is counted only once.
Return a list of dictionaries, one per calendar day in ascending order, each containing:
"date": the day formatted as"YYYY-MM-DD"."dau": the DAU value for that day."mau_l30d": the rolling 30-day MAU value for that day.
Important rules:
- The output must include every calendar day in the range, even days with zero login activity (
dau = 0). Do not skip days that have no records. - Login records whose timestamp falls before
start_datestill contribute to MAU windows for days inside the range (because the 30-day lookback can reach earlier dates). Login records afterend_dateare irrelevant and can be ignored. - If
start_dateis later thanend_date, return an empty list. - If the login list is empty, every day in the range has
dau = 0andmau_l30d = 0.
Constraints:
start_dateandend_dateare valid date strings in"YYYY-MM-DD"format.- The date range spans at most 366 days.
loginshas at most 100,000 records.user_idvalues are positive integers.login_tsstrings are valid ISO-8601 timestamps, possibly suffixed withZfor UTC.
Examples
Example 1
Input: active_user_metrics('2023-01-01', '2023-01-04', [{'user_id': 1, 'login_ts': '2023-01-01T10:00:00Z'}, {'user_id': 1, 'login_ts': '2023-01-01T18:00:00Z'}, {'user_id': 2, 'login_ts': '2023-01-03T09:00:00Z'}])
Output: [{'date': '2023-01-01', 'dau': 1, 'mau_l30d': 1}, {'date': '2023-01-02', 'dau': 0, 'mau_l30d': 1}, {'date': '2023-01-03', 'dau': 1, 'mau_l30d': 2}, {'date': '2023-01-04', 'dau': 0, 'mau_l30d': 2}]
Hints
Hint 1
Build a dictionary mapping each calendar day to a set of distinct user_ids who logged in that day. Using a set automatically deduplicates repeat logins.
Hint 2
Iterate over every date in the range from start to end so that zero-activity days are naturally included with dau = 0. Do not iterate over the logins themselves.
Hint 3
For each output day, union the per-day user sets across the 30-day lookback window [d-29, d] to compute distinct MAU. Do not sum the daily DAU values, as that would double-count users active on multiple days.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has three stages:
-
Bucket logins by calendar day. Parse each record's
login_ts, extract the date, and store theuser_idin a set keyed by that date. Using a set means a user who logs in multiple times on the same day is only counted once. Importantly, we keep logins from beforestart_datein this map because MAU windows for early dates in the range may reach backwards. -
Drive output from a calendar loop. Iterate from
start_datetoend_dateone day at a time. For each day, look up its user set in the map (defaulting to an empty set). This guarantees zero-activity days appear in the output withdau = 0. If we instead iterated over the login records, days with no activity would simply be absent. -
Compute rolling MAU with a set union. For each output day
d, the 30-day window is[d - 29, d]. We collect the per-day user sets for all 30 days and take their union. The size of this union is the distinct count of users active in the window. We cannot sum daily DAU values because a user active on multiple days would be counted multiple times.
Why it is correct
- DAU correctness: The per-day set contains exactly the distinct users with a login timestamp on that calendar date. Its length is the DAU by definition.
- Zero days: The calendar loop visits every date in the range. A date with no logins maps to an empty set, yielding
dau = 0. The MAU may still be positive if there was activity in the preceding 29 days. - MAU correctness: The 30-day lookback covers dates
d-29throughd, which is exactly 30 calendar days includingd. Unioning the per-day sets eliminates double-counting. Keeping pre-range logins ensures MAU on the first day of the range correctly reflects December activity, not an artificial ramp-up. - Edge cases: An empty login list means every per-day set is empty, so all DAU and MAU values are 0. If
start_date > end_date, the while loop never executes and an empty list is returned.
Complexity
Let L be the number of login records, D the number of days in the output range, and U the maximum number of distinct users in any 30-day window.
- Time: O(L) to bucket all logins, plus O(D · 30 · U_day) to build the 30-day unions where
U_dayis the average daily distinct user count. Worst case O(D · U · 30). Fine for a one-year range with typical screen-scale data. - Space: O(L) for the per-day sets, O(U) for the temporary union set, and O(D) for the output list.
A sliding-window optimization using a Counter (incrementing user counts as days enter the window and decrementing as days leave) reduces the total to O(L + D) amortized, but the union approach is simpler and easier to verify.
from typing import List, Dict
def active_user_metrics(start_date: str, end_date: str, logins: List[Dict]) -> List[Dict]:
from datetime import datetime, timedelta
from collections import defaultdict
# Parse the range boundaries into date objects
start = datetime.strptime(start_date, "%Y-%m-%d").date()
end = datetime.strptime(end_date, "%Y-%m-%d").date()
# Map each calendar day to the set of distinct users who logged in that day.
# Keep all logins (even before start_date) so MAU lookback works correctly.
daily_users: Dict = defaultdict(set)
for record in logins:
ts = datetime.fromisoformat(record["login_ts"].replace("Z", "+00:00"))
day = ts.date()
daily_users[day].add(record["user_id"])
# Walk every calendar day in the range so zero-activity days are included
results = []
current = start
while current <= end:
# DAU: distinct users whose login falls on this exact day
dau = len(daily_users.get(current, set()))
# MAU (last 30 days): union of distinct users across [current-29, current]
window_users = set()
lookback_start = current - timedelta(days=29)
for offset in range(30):
window_users.update(daily_users.get(lookback_start + timedelta(days=offset), set()))
results.append({
"date": current.strftime("%Y-%m-%d"),
"dau": dau,
"mau_l30d": len(window_users),
})
current += timedelta(days=1)
return results