First Long Run of Daily Activity per User
Arrays & HashingAuto-graded · 16 test casesLast updated
Group activity logs by user, dedupe dates, find maximal consecutive-day runs of length 7 or more, and report each user's earliest such run.
First Long Run of Daily Activity per User
You have a list of activity log entries from a platform. Each entry is a dictionary with two keys:
"user_id": identifies the user."active_date": a calendar date as an ISO string,"YYYY-MM-DD".
A user can have several entries on the same date.
Task
Implement first_long_run(records). For every user, find their earliest run of at least 7 consecutive calendar days on which they were active. Return one result dictionary per qualifying user.
Definitions and rules
- A user is active on a date if at least one entry for that user has that date. Several entries on one date count as a single active day.
- A run is a maximal block of consecutive calendar days that are all active days for the user. It cannot be extended by the day before its first date or the day after its last date. Use real calendar arithmetic, so month, year and leap-day boundaries (for example Feb 28, Feb 29, Mar 1) continue a run.
- A run qualifies if it covers 7 or more days.
- If a qualifying run is longer than 7 days, report the full run: its first and last dates, not just the first seven days.
- If a user has several qualifying runs, report only the one with the earliest start date. Shorter runs that come earlier do not matter, because only qualifying runs are compared.
- Users with no qualifying run do not appear in the output.
- Ignore any entry where
"user_id"or"active_date"is missing orNone.
Output
Return a list of dictionaries, one per qualifying user, each with exactly these keys:
"user_id": the user's id, with the same value and type as in the input."start_date": the first date of the run, as"YYYY-MM-DD"."end_date": the last date of the run, as"YYYY-MM-DD".
Sort the list in ascending order of "user_id", comparing the values as given in the input. If the ids are strings, the comparison is lexicographic, so "10" comes before "2". If there are no qualifying users, return an empty list.
Constraints
0 <= len(records) <= 10^5- All dates are valid ISO dates (
YYYY-MM-DD). - All
user_idvalues in one call share the same type and can be compared with each other. - Entries may appear in any order.
Examples
Example 1
Input: first_long_run([{'user_id': 1, 'active_date': '2024-01-01'}, {'user_id': 1, 'active_date': '2024-01-01'}, {'user_id': 1, 'active_date': '2024-01-02'}, {'user_id': 1, 'active_date': '2024-01-03'}, {'user_id': 1, 'active_date': '2024-01-04'}, {'user_id': 1, 'active_date': '2024-01-05'}, {'user_id': 1, 'active_date': '2024-01-06'}, {'user_id': 1, 'active_date': '2024-01-07'}, {'user_id': 1, 'active_date': '2024-01-08'}, {'user_id': 1, 'active_date': '2024-02-01'}, {'user_id': 2, 'active_date': '2024-01-01'}, {'user_id': 2, 'active_date': '2024-01-02'}, {'user_id': 2, 'active_date': '2024-01-03'}, {'user_id': 3, 'active_date': '2024-03-01'}, {'user_id': 3, 'active_date': '2024-03-02'}, {'user_id': 3, 'active_date': '2024-03-03'}, {'user_id': 3, 'active_date': '2024-03-04'}, {'user_id': 3, 'active_date': '2024-03-05'}, {'user_id': 3, 'active_date': '2024-03-06'}, {'user_id': 3, 'active_date': '2024-03-07'}])
Output: [{'user_id': 1, 'start_date': '2024-01-01', 'end_date': '2024-01-08'}, {'user_id': 3, 'start_date': '2024-03-01', 'end_date': '2024-03-07'}]
Hints
Hint 1
Collapse duplicates first: for each user, keep a set of distinct dates. Two entries on the same day must not count as two days.
Hint 2
Sort each user's distinct dates, then scan them. A new run begins whenever a date is not exactly one day after the previous one.
Hint 3
Close a run when it ends and check its length (last - first) in days >= 6. Remember to close the final run after the loop, and keep only the first qualifying run per user since runs are found in date order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a "find maximal consecutive runs" problem, handled independently for each user.
- Group and deduplicate. Walk through the records, skipping any with a missing user or date. For each user, store the parsed dates in a set, so several entries on one day collapse into one active day.
- Sort each user's dates. After sorting, consecutive calendar days sit next to each other.
- Scan for runs. Keep the start of the current run and the previous date. If the next date is exactly one day after the previous one, the run continues. Otherwise the current run has ended at the previous date. If its length is at least 7 days (
last - first >= 6days), it qualifies. - Take the earliest qualifying run. Dates are scanned in increasing order, so the first qualifying run found has the earliest start. The scan can stop there. If the scan finishes without a qualifying run, the last run is still open and must be checked after the loop.
- Sort the output by
user_id.
Why it is correct
- After deduplication, a user's sorted dates are strictly increasing, so two neighbouring dates are either exactly one day apart (same run) or further apart (a gap that ends the run). Each run found is therefore maximal.
- Because a maximal run is reported with its true first and last dates, runs longer than 7 days are returned in full.
- Runs are produced in chronological order. The first one meeting the 7-day threshold is the earliest qualifying run, even if shorter, non-qualifying runs came before it.
- Real date arithmetic (
timedelta) handles month, year and leap-day boundaries correctly. - Checking the last run after the loop covers streaks that end on the user's final active date.
Complexity
Let n be the number of records. Building the sets takes O(n) on average. Sorting each user's distinct dates costs O(m log m) in total over m distinct (user, date) pairs, and the scans are linear in m. Sorting the output adds O(u log u) for u qualifying users. Overall this is O(n log n) time and O(m) space.
Reference solution
from datetime import date, timedelta
from typing import Dict, List
def first_long_run(records: List[Dict[str, str]]) -> List[Dict[str, str]]:
dates_by_user = {}
for rec in records:
uid = rec.get("user_id")
d = rec.get("active_date")
if uid is not None and d is not None:
dates_by_user.setdefault(uid, set()).add(date.fromisoformat(d))
out = []
one_day = timedelta(days=1)
for uid, dates in dates_by_user.items():
run_start = None
prev = None
found = None
for d in sorted(dates):
if prev is not None and d == prev + one_day:
prev = d
continue
# a run (if any) just ended at prev
if run_start is not None and (prev - run_start).days >= 6:
found = (run_start, prev)
break
run_start = d
prev = d
if found is None and run_start is not None and (prev - run_start).days >= 6:
found = (run_start, prev)
if found is not None:
out.append({
"user_id": uid,
"start_date": found[0].isoformat(),
"end_date": found[1].isoformat(),
})
out.sort(key=lambda r: r["user_id"])
return out