Weekly Totals with 3-Week Rolling Sum in Pacific Time
SQL & DataAuto-graded · 19 test casesLast updated
Bucket timestamped payments into Pacific-time Monday weeks, fill empty weeks with zero, and report weekly and trailing three-week totals.
You are given a list of payment events, each recorded as an absolute instant with a UTC offset. Produce a week-by-week report in America/Los_Angeles local time, containing each week's total and a trailing three-week total.
Input
records: a list of rows[user_id, event_ts, amount].user_idis an integer. It plays no role in the computation.event_tsis an ISO-8601 timestamp string that includes a UTC offset, for example"2025-08-05T18:30:00+00:00". A trailingZalso means UTC.amountis a decimal value given as a string, such as"12.00".
range_start: a date string"YYYY-MM-DD", the first week of the report.range_end: a date string"YYYY-MM-DD", the last date that a report week may start on.
Task
- Report weeks. The report contains one row per week start date:
range_start,range_start + 7 days,range_start + 14 days, and so on, up to and includingrange_end. You may assumerange_startis a Monday. Ifrange_startis later thanrange_end, return an empty list. - Assigning events to weeks. Convert each
event_tsto Los Angeles local time (with correct daylight-saving handling) first. Take the local calendar date, then move back to that week's Monday (weeks run Monday through Sunday). That Monday is the event's week. An event is counted only if its Monday is one of the report weeks. Events in any other week are ignored. - Weekly total. For every report week,
week_totalis the sum of the amounts of its events. A week with no events has total0. - Rolling total. For every report week,
rolling_totalis the sum ofweek_totalfor that week and the two report weeks directly before it. For the first or second report week, only the report weeks that exist are summed. Events beforerange_startnever contribute. - Only the event timestamp matters. Do not use any other notion of when a row arrived.
Output
Return a list with one row per report week, in ascending date order. Each row is [week_start, week_total, rolling_total], where:
week_startis the Monday as an ISO date string"YYYY-MM-DD",week_totalandrolling_totalare numbers rounded to two decimal places.
Sum the amounts exactly as decimals, then round the totals to two decimals and return them as floats.
Constraints
0 <= len(records) <= 10^5- Every
event_tsincludes a UTC offset. - Amounts are decimal strings with at most two fractional digits.
- Events close to local midnight must land in the correct Los Angeles week, including across daylight-saving changes.
- The number of report weeks is at most about
10^4.
Examples
Example 1
Input: rolling_weekly_totals([[1, '2025-08-04T16:00:00+00:00', '12.00'], [2, '2025-08-05T18:30:00+00:00', '7.50'], [1, '2025-08-12T20:10:00+00:00', '5.00'], [3, '2025-08-19T15:05:00+00:00', '9.00'], [2, '2025-08-20T02:45:00+00:00', '11.00'], [1, '2025-08-26T12:00:00+00:00', '3.00'], [2, '2025-09-02T21:10:00+00:00', '8.00'], [3, '2025-09-09T14:25:00+00:00', '10.00']], '2025-08-04', '2025-09-15')
Output: [['2025-08-04', 19.5, 19.5], ['2025-08-11', 5, 24.5], ['2025-08-18', 20, 44.5], ['2025-08-25', 3, 28], ['2025-09-01', 8, 31], ['2025-09-08', 10, 21], ['2025-09-15', 0, 18]]
Hints
Hint 1
Convert each timestamp to the Los Angeles zone before doing anything with its date. Taking the UTC date first puts late-Sunday local events in the wrong week.
Hint 2
Once you have the local date, subtracting its weekday index (Monday = 0) gives the Monday of its week. Use a dictionary keyed by Monday dates, pre-filled with zeros for every report week.
Hint 3
Because every report week is present in the dictionary, the rolling total for week i is just the sum of the totals at positions i-2, i-1 and i in the sorted list. Use Decimal to avoid float drift.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Build the calendar first. Create a dictionary keyed by each report week's start date (
range_start, then every 7 days up torange_end), each initialised toDecimal('0.00'). Because every week is present up front, empty weeks are handled automatically and the rolling window never has gaps. - Convert, then bucket. For each record, parse the timestamp (it carries an offset), convert it to
America/Los_Angeleswithzoneinfo, and take the local date. Subtractweekday()days to get the Monday of that week.zoneinfoapplies the correct offset (PDT or PST) per instant, so daylight-saving changes need no special code. - Accumulate. If that Monday is a key in the dictionary, add the amount, parsed as a
Decimal. Otherwise the event is outside the report and is skipped. - Roll. Sort the week keys. For the week at index
i, sum the totals at indicesmax(0, i-2)throughi. The calendar is gap-free, so "the two previous rows" means exactly "the two previous weeks". Early weeks naturally use fewer terms. - Format. Round to two decimals and return the date as an ISO string and the totals as floats.
Why it is correct
- Converting to local time before taking the date ensures an event such as Sunday 23:30 in Los Angeles stays in that Sunday's week, even though it is Monday in UTC.
- Using
Decimalavoids floating-point error in the sums. Conversion tofloathappens only at the end. - Pre-filling the calendar guarantees every week appears with zero when it has no events.
- The window is defined over report weeks only, so events before
range_startare never included, matching the rules.
Complexity
- Time: O(N + W log W), where N is the number of records and W the number of report weeks. The sort is on already nearly ordered keys and is negligible. Each rolling sum uses at most 3 terms.
- Space: O(W) for the totals dictionary and the output.
Reference solution
from datetime import datetime, date, timedelta
from decimal import Decimal
from zoneinfo import ZoneInfo
from typing import List
def rolling_weekly_totals(records: List[List[str]], range_start: str, range_end: str) -> List[List[object]]:
la = ZoneInfo('America/Los_Angeles')
start = date.fromisoformat(range_start)
end = date.fromisoformat(range_end)
if start > end:
return []
totals = {}
current = start
while current <= end:
totals[current] = Decimal('0.00')
current += timedelta(days=7)
for row in records:
ts = datetime.fromisoformat(row[1].replace('Z', '+00:00'))
if ts.tzinfo is None:
raise ValueError('event_ts must include a timezone')
local_date = ts.astimezone(la).date()
monday = local_date - timedelta(days=local_date.weekday())
if monday in totals:
totals[monday] += Decimal(str(row[2]))
result = []
weeks = sorted(totals)
for i, week in enumerate(weeks):
rolling = sum((totals[weeks[j]] for j in range(max(0, i - 2), i + 1)), Decimal('0.00'))
result.append([
week.isoformat(),
float(totals[week].quantize(Decimal('0.01'))),
float(rolling.quantize(Decimal('0.01'))),
])
return result