Seven-Day Spend Grid per Shopper Using Only String Dates
Arrays & HashingAuto-graded · 17 test casesLast updated
Aggregate (shopper, date, amount) records into per-shopper totals for a 7-day window, using hand-written ISO date stepping and hashing instead of date libraries.
Seven-Day Spend Grid per Shopper
You receive a list of purchase records. Each record is a list [shopper_id, date, amount], where date is an ISO string "YYYY-MM-DD" (zero-padded). You also receive a window given by window_start and window_end, both ISO date strings. The window is inclusive and covers exactly 7 consecutive calendar days.
Build a table with one row per shopper. Each row has the form:
[shopper_id, t0, t1, t2, t3, t4, t5, t6]
where ti is the total amount over all of that shopper's records dated exactly window_start + i days.
Rules
- Records may come in any order. Several records may share the same shopper and date; add all of them together. Do not treat them as duplicates to discard.
- A day with no records for a shopper contributes
0. - Records dated outside the window are ignored.
- Only shoppers with at least one record inside the window appear in the output. A shopper whose records all fall outside the window is omitted.
- Output rows are sorted in ascending order by
shopper_id(natural ordering of the ids; within one input all ids have the same type). - Amounts may be negative (refunds) and are summed as given.
- You may not use any date/time library. You need to work out the 7 consecutive dates yourself, including month ends, year ends, and leap years (Gregorian rule: divisible by 4, except centuries, unless divisible by 400).
- If there are no records inside the window, return an empty list.
Constraints
0 <= len(records) <= 10^5window_startandwindow_endare valid ISO dates andwindow_endis exactly 6 days afterwindow_start.- Every record's date is a valid zero-padded
YYYY-MM-DDstring. shopper_idis an int or a string;amountis a number.- The window may cross a month boundary, a year boundary, or contain February 29.
Examples
Example 1
Input: weekly_spend_table([[1, '2024-02-01', 10], [1, '2024-02-03', 5], [2, '2024-02-02', 7], [1, '2024-02-01', 2]], '2024-02-01', '2024-02-07')
Output: [[1, 12, 0, 5, 0, 0, 0, 0], [2, 0, 7, 0, 0, 0, 0, 0]]
Example 2
Input: weekly_spend_table([['s2', '2023-12-31', 4], ['s1', '2024-01-01', 3], ['s2', '2024-01-01', 6]], '2023-12-31', '2024-01-06')
Output: [['s1', 0, 3, 0, 0, 0, 0, 0], ['s2', 4, 6, 0, 0, 0, 0, 0]]
Hints
Hint 1
ISO dates with zero padding compare in the same order as chronological order, so you never need to parse a date to compare two of them.
Hint 2
Generate the seven date strings once by writing a small 'next day' function (days in month, leap year, month/year rollover), then map each date string to its column index 0..6 in a dictionary.
Hint 3
Keep a dictionary from shopper_id to a list of seven zeros, created the first time you see that shopper in the window, add each amount at its column, and sort the keys at the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Enumerate the window. Start from
window_startand repeatedly apply a hand-writtenstepfunction that returns the next calendar day. It increments the day; if that exceeds the month's length it moves to day 1 of the next month; after December it moves to January 1 of the next year. February has 29 days in leap years (divisible by 4, except centuries not divisible by 400). This gives the seven date strings in order. - Map date to column. Store a dictionary
column[date_string] = i. A record's column is then a single lookup, with no date subtraction needed. A date not in the dictionary lies outside the window and is skipped. - Aggregate in one pass. Keep
totals[shopper_id]as a list of seven zeros, created the first time that shopper has an in-window record. Add each amount at its column. Days without records keep their initial0, and several records on the same day simply accumulate. - Emit. Sort the shopper ids and output
[shopper_id] + totals[shopper_id]for each.
Why it is correct
stepimplements the calendar exactly, so thei-th generated string iswindow_start + idays.- Each in-window record is added to exactly the cell for its shopper and day. Addition is commutative, so input order does not matter, and each cell ends as the sum of all matching amounts.
- Out-of-window records have no dictionary entry and are ignored, so shoppers with only such records never get a row.
- Untouched cells stay
0, which is the required value for missing days.
Complexity
- Time: O(n + S log S), where n is the number of records and S is the number of distinct shoppers in the window (the log term comes from the final sort). Building the window is O(7).
- Space: O(S) for the totals, with 7 numbers per shopper.
Reference solution
from typing import List
def weekly_spend_table(records: List[List], window_start: str, window_end: str) -> List[List]:
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def step(date_str):
year = int(date_str[0:4])
month = int(date_str[5:7])
day = int(date_str[8:10])
lengths = [31, 29 if is_leap(year) else 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31]
if day < lengths[month - 1]:
day += 1
elif month < 12:
month += 1
day = 1
else:
year += 1
month = 1
day = 1
return f"{year:04d}-{month:02d}-{day:02d}"
days = [window_start]
while days[-1] != window_end and len(days) < 7:
days.append(step(days[-1]))
column = {d: i for i, d in enumerate(days)}
totals = {}
for shopper_id, date_str, amount in records:
col = column.get(date_str)
if col is None:
continue
if shopper_id not in totals:
totals[shopper_id] = [0] * 7
totals[shopper_id][col] += amount
return [[sid] + totals[sid] for sid in sorted(totals)]