Top Three Categories by Average October Sale Value
SQL & DataAuto-graded · 12 test casesLast updated
Filter records to one month, group by key, apply a minimum-count threshold, compute a rounded average, and return the top three groups, mirroring a SQL WHERE/GROUP BY/HAVING/ORDER BY/LIMIT pipeline.
Best Categories by Average Sale Value
An online marketplace keeps its transactions and its product categories as two lists of dictionaries, which stand in for database tables.
sales (each dictionary has these keys)
| Key | Type | Meaning |
|---|---|---|
sale_id | int | Unique id of the sale |
category_id | int | Refers to a category_id in categories |
seller_id | int | Id of the seller |
sale_date | str | Date in YYYY-MM-DD format |
revenue | str or number | Revenue of the sale in USD (convertible with float(...)) |
categories (each dictionary has these keys)
| Key | Type | Meaning |
|---|---|---|
category_id | int | Unique id of the category |
category_name | str | Display name of the category |
Task
Write a function that finds the three categories with the highest average revenue per sale in October 2023.
- Consider only sales whose
sale_datefalls in October 2023 (dates from2023-10-01through2023-10-31). - Group these sales by
category_id. - Drop every category that has fewer than 10 October sales. A category with exactly 10 sales stays.
- For each remaining category, compute:
total_revenue: the sum offloat(revenue)over its October sales, added up in the order the sales appear in the input, with no rounding.average_revenue_per_sale:total_revenuedivided by the number of its October sales, rounded to 2 decimal places with Python's built-inround(x, 2).
- Sort by
average_revenue_per_sale(the rounded value) from highest to lowest and return at most the first 3 entries.
Output format
Return a list of dictionaries, each with exactly these keys:
category_name: the name looked up fromcategories.total_revenue: a number. If the value is a whole number, give it as anint(for example1500). Otherwise give the float.average_revenue_per_sale: the rounded average, with the same rule (anintwhen it is a whole number, otherwise a float).
Tie-breaking and edge cases
- If several categories have the same rounded average, they keep the order in which each category first appeared among the October sales in
sales. Use a stable sort. - If fewer than 3 categories qualify, return only those. If none qualify, return an empty list.
- Sales outside October 2023, including 30 September and 1 November, never count toward any total or count.
- Every
category_idinsalesis guaranteed to exist incategories.
Constraints
0 <= len(sales) <= 10^50 <= len(categories) <= 10^4sale_dateis always a valid string inYYYY-MM-DDformat.revenueis always convertible to a float and is never missing.- Category ids in
categoriesare unique.
Examples
Example 1
Input: top_categories_by_avg_sale([{'sale_id': 1, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-01', 'revenue': '100.00'}, {'sale_id': 2, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-02', 'revenue': '100.00'}, {'sale_id': 3, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-03', 'revenue': '100.00'}, {'sale_id': 4, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-04', 'revenue': '100.00'}, {'sale_id': 5, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-05', 'revenue': '100.00'}, {'sale_id': 6, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-06', 'revenue': '100.00'}, {'sale_id': 7, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-07', 'revenue': '100.00'}, {'sale_id': 8, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-08', 'revenue': '100.00'}, {'sale_id': 9, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-09', 'revenue': '100.00'}, {'sale_id': 10, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-10', 'revenue': '100.00'}, {'sale_id': 11, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-11', 'revenue': '100.00'}, {'sale_id': 12, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-12', 'revenue': '100.00'}, {'sale_id': 13, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-13', 'revenue': '100.00'}, {'sale_id': 14, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-14', 'revenue': '100.00'}, {'sale_id': 15, 'category_id': 1, 'seller_id': 7, 'sale_date': '2023-10-15', 'revenue': '100.00'}, {'sale_id': 16, 'category_id': 2, 'seller_id': 8, 'sale_date': '2023-10-01', 'revenue': '20.00'}, {'sale_id': 17, 'category_id': 2, 'seller_id': 8, 'sale_date': '2023-10-02', 'revenue': '20.00'}, {'sale_id': 18, 'category_id': 2, 'seller_id': 8, 'sale_date': '2023-10-03', 'revenue': '20.00'}, {'sale_id': 19, 'category_id': 2, 'seller_id': 8, 'sale_date': '2023-10-04', 'revenue': '20.00'}, {'sale_id': 20, 'category_id': 2, 'seller_id': 8, 'sale_date': '2023-10-05', 'revenue': '20.00'}], [{'category_id': 1, 'category_name': 'Electronics'}, {'category_id': 2, 'category_name': 'Books'}])
Output: [{'category_name': 'Electronics', 'total_revenue': 1500, 'average_revenue_per_sale': 100}]
Hints
Hint 1
Think of the work as a pipeline: filter rows by month, group by category, filter groups by count, compute the metric, sort, and cut to three.
Hint 2
Build a dictionary from category_id to category_name first, then make one pass over the sales, keeping a count and a running revenue sum for each category whose sale_date starts with '2023-10'.
Hint 3
Sort on the already-rounded average using a stable sort, and iterate categories in first-seen order so ties resolve correctly. Convert whole-valued floats to int before returning.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a SQL-style pipeline written in Python:
- Lookup (join). Build a dictionary mapping
category_idtocategory_nameso names can be attached at the end. - Filter and group (
WHERE+GROUP BY). Walk throughsalesonce. For each sale whose date string starts with2023-10, update that category's counter and running revenue sum. Because the dates are zero-padded ISO strings, this prefix check selects exactly October 2023. - Filter groups (
HAVING). After the pass, discard categories with a count below 10. The count only exists after grouping, which is why this step comes after the loop and not inside it. - Compute metrics. The average is
total / count, rounded to 2 decimals. Whole-valued numbers are converted tointto match the required output format. - Sort and limit (
ORDER BY ... LIMIT 3). Sort by the rounded average in descending order and slice the first three.
Why it is correct
- Each October sale is counted exactly once, in its own category's group. Sales from other months never touch the accumulators.
- The threshold test is
count >= 10, so exactly 10 sales qualifies and 9 does not. - The ranking value is exactly the defined metric, rounded the same way the output reports it.
- Python's
dictkeeps insertion order andlist.sortis stable. Categories with equal rounded averages therefore stay in the order of their first October sale, which is the required tie-break. - Revenue is summed in input order with
float, so the totals match the expected values exactly.
Complexity
- Time: O(S + C + G log G), where S is the number of sales, C the number of categories and G the number of qualifying categories (G <= C).
- Space: O(C) for the name lookup and the per-category accumulators.
Reference solution
from collections import defaultdict
from typing import List, Dict
def top_categories_by_avg_sale(sales: List[Dict], categories: List[Dict]) -> List[Dict]:
# Lookup: category_id -> category_name
names = {c['category_id']: c['category_name'] for c in categories}
# Single pass: keep only October 2023 sales, accumulate per category
stats = defaultdict(lambda: {'count': 0, 'total': 0.0})
for sale in sales:
if sale['sale_date'].startswith('2023-10'):
entry = stats[sale['category_id']]
entry['count'] += 1
entry['total'] += float(sale['revenue'])
# Keep categories with at least 10 sales and compute the metrics
results = []
for category_id, entry in stats.items():
if entry['count'] < 10:
continue
total = entry['total']
average = round(total / entry['count'], 2)
if total == int(total):
total = int(total)
if average == int(average):
average = int(average)
results.append({
'category_name': names[category_id],
'total_revenue': total,
'average_revenue_per_sale': average,
})
# Stable sort, highest average first, then keep the top three
results.sort(key=lambda r: r['average_revenue_per_sale'], reverse=True)
return results[:3]