Daily Leading Buyers Among Active Subscribers
SQL & DataAuto-graded · 15 test casesLast updated
Filter orders by inclusive membership windows, total quantities per day and customer, and return every customer tied for each day's maximum, in sorted order.
Daily Leading Buyers Among Active Subscribers
A shop runs a subscription program. You are given two tables, each as a list of dictionaries whose values are all strings.
Subscriptions (subscriptions): each row has these keys:
Customer_IDStart_DateEnd_Date
A row means the customer was subscribed from Start_Date through End_Date. Both endpoints are included. A customer may have several rows, and those rows may overlap or repeat.
Purchases (purchases): each row has these keys:
Customer_IDOrder_IDOrder_DayProduct_IDQuantity_Sold(an integer written as a string)
For every calendar day, find the customer or customers who bought the most units that day, counting only purchases made while the customer held an active subscription.
Rules
- A purchase counts only if at least one of that customer's subscription rows satisfies
Start_Date <= Order_Day <= End_Date. A purchase counts once, even if several subscription rows cover its day. - Purchases from customers with no subscription row, or placed outside every one of their windows, are ignored.
- For each
(Order_Day, Customer_ID)pair, add up theQuantity_Soldof all counted purchases. - For each day, keep every customer whose total equals that day's maximum. Ties produce several rows.
- A day with no counted purchases produces no output.
Output
Return a list of dictionaries, each with these keys:
Order_Day(string)Customer_ID(string)Total_Quantity_Sold(int)
Order the rows by Order_Day ascending, then by Customer_ID ascending. Compare Customer_ID values as strings, so "10" comes before "2". Dates are in YYYY-MM-DD format, so string comparison matches chronological order.
If there are no qualifying rows, return an empty list.
Constraints
Customer_IDvalues andQuantity_Soldvalues arrive as strings. Convert quantities to integers and treat IDs as strings.- Dates are ISO
YYYY-MM-DDstrings. - Either input list may be empty.
- A customer may have zero, one, or many subscription rows, and those rows may overlap.
- A customer may place several purchases on the same day.
Examples
Example 1
Input: daily_top_subscriber_buyers([{'Customer_ID': '1', 'Start_Date': '2025-01-01', 'End_Date': '2025-12-31'}, {'Customer_ID': '2', 'Start_Date': '2025-03-15', 'End_Date': '2025-10-15'}], [{'Customer_ID': '1', 'Order_ID': '1001', 'Order_Day': '2025-04-01', 'Product_ID': 'P123', 'Quantity_Sold': '3'}, {'Customer_ID': '1', 'Order_ID': '1002', 'Order_Day': '2025-04-01', 'Product_ID': 'P456', 'Quantity_Sold': '2'}, {'Customer_ID': '2', 'Order_ID': '1003', 'Order_Day': '2025-04-01', 'Product_ID': 'P123', 'Quantity_Sold': '6'}])
Output: [{'Order_Day': '2025-04-01', 'Customer_ID': '2', 'Total_Quantity_Sold': 6}]
Example 2
Input: daily_top_subscriber_buyers([{'Customer_ID': '1', 'Start_Date': '2025-01-01', 'End_Date': '2025-12-31'}, {'Customer_ID': '2', 'Start_Date': '2025-01-01', 'End_Date': '2025-12-31'}], [{'Customer_ID': '1', 'Order_ID': '1', 'Order_Day': '2025-05-01', 'Product_ID': 'A', 'Quantity_Sold': '4'}, {'Customer_ID': '2', 'Order_ID': '2', 'Order_Day': '2025-05-01', 'Product_ID': 'B', 'Quantity_Sold': '4'}])
Output: [{'Order_Day': '2025-05-01', 'Customer_ID': '1', 'Total_Quantity_Sold': 4}, {'Order_Day': '2025-05-01', 'Customer_ID': '2', 'Total_Quantity_Sold': 4}]
Hints
Hint 1
Build a map from customer to the list of their (start, end) subscription windows, then check each purchase against that list.
Hint 2
Use an any(...) style check rather than joining, so overlapping or duplicate subscription rows never count the same purchase twice.
Hint 3
Accumulate totals keyed by (day, customer), group them by day, take the maximum per day, and emit every customer matching it in sorted ID order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a "top per group" problem where the group is a calendar day. It has three steps.
- Filter by subscription. Build a dictionary mapping each customer to the list of their
(start, end)windows. A purchase is counted only ifany(start <= day <= end)holds for that customer's windows. Usinganymeans a purchase is counted at most once, even when windows overlap or are duplicated. A join would instead inflate totals. - Aggregate. Add the quantity of each counted purchase into a total keyed by
(day, customer). - Pick the leaders per day. Group the totals by day, find the maximum total for that day, and output every customer whose total equals it. Sorting days, and customer IDs as strings within a day, gives the required order.
Why it is correct
- A purchase contributes to a total exactly when some subscription window contains its day, with both endpoints included.
- After aggregation, each
(day, customer)pair has one total. Comparing it to the day's maximum selects exactly the tied leaders and nobody else. - Days with no counted purchases never appear in the totals, so they produce no output.
- Dates are ISO strings, so lexicographic comparison equals chronological comparison and no parsing is needed.
- Filtering happens before aggregation, so non-subscribed purchases never affect a total or a maximum.
Complexity
Let P be the number of subscription rows, O the number of purchases, m the maximum number of windows per customer, and K the number of distinct qualifying (day, customer) pairs.
- Time: O(P + O * m + K log K).
- Space: O(P + K).
Reference solution
from collections import defaultdict
from typing import Dict, List
def daily_top_subscriber_buyers(subscriptions: List[Dict[str, str]], purchases: List[Dict[str, str]]) -> List[Dict[str, object]]:
windows = {}
for row in subscriptions:
customer = str(row["Customer_ID"])
windows.setdefault(customer, []).append((row["Start_Date"], row["End_Date"]))
totals = defaultdict(int)
for row in purchases:
customer = str(row["Customer_ID"])
day = row["Order_Day"]
if any(start <= day <= end for start, end in windows.get(customer, [])):
totals[(day, customer)] += int(row["Quantity_Sold"])
by_day = defaultdict(list)
for (day, customer), total in totals.items():
by_day[day].append((customer, total))
result = []
for day in sorted(by_day):
highest = max(total for _, total in by_day[day])
for customer, total in sorted(by_day[day]):
if total == highest:
result.append({
"Order_Day": day,
"Customer_ID": customer,
"Total_Quantity_Sold": total,
})
return result