Category Revenue and Fulfillment Report from Three Tables
Arrays & HashingAuto-graded · 17 test casesLast updated
Join order, product and category records, group by category name, and compute total revenue, mean revenue per row and the share of completed rows, using hash maps.
Category Revenue and Fulfillment Report
A delivery marketplace stores its data in three lists of dictionaries:
orders: each entry hasorder_id,product_id,quantity,unit_priceandstatus.products: each entry hasproduct_idandcategory_id.categories: each entry hascategory_idandcategory_name.
Write a function that links these tables and produces one summary record per category name.
Joining
Treat the link as an inner join. An order row is used only if its product_id appears in products and that product's category_id appears in categories. Any other order row is ignored completely.
If the same product_id appears more than once in products, the last entry in the list wins. The same rule applies to a repeated category_id in categories.
Grouping
Group the surviving order rows by category_name (not by category_id). If two different category ids share a name, their rows belong to the same group.
Metrics for each group
Every surviving order row counts as one "order line", whatever its status.
total_sales: the sum ofquantity * unit_priceover all rows in the group.average_sales_per_order:total_salesdivided by the number of rows in the group.completion_rate: the number of rows whosestatusis exactly"completed"(case-sensitive) divided by the number of rows in the group.
Rows that are not completed still contribute to total_sales and to the row count. The status only influences completion_rate.
Output
Return a list of dictionaries, one per group, each with the keys category_name, total_sales, average_sales_per_order and completion_rate. Sort the list by category_name in ascending order. Categories with no surviving order rows must not appear. If no rows survive, return an empty list.
Constraints
0 <= len(orders) <= 10^50 <= len(products), len(categories) <= 10^5quantityandunit_priceare non-negative numbers (integers or floats).statusis a string.- Category names are strings and can be compared with the usual ordering.
Examples
Example 1
Input: summarize_category_sales([{'order_id': 1, 'product_id': 10, 'quantity': 2, 'unit_price': 5, 'status': 'completed'}, {'order_id': 2, 'product_id': 11, 'quantity': 1, 'unit_price': 8, 'status': 'cancelled'}, {'order_id': 3, 'product_id': 10, 'quantity': 3, 'unit_price': 5, 'status': 'completed'}], [{'product_id': 10, 'category_id': 1}, {'product_id': 11, 'category_id': 1}], [{'category_id': 1, 'category_name': 'Meals'}])
Output: [{'category_name': 'Meals', 'total_sales': 33, 'average_sales_per_order': 11, 'completion_rate': 0.6666666666666666}]
Example 2
Input: summarize_category_sales([{'order_id': 1, 'product_id': 1, 'quantity': 1, 'unit_price': 12.5, 'status': 'completed'}, {'order_id': 2, 'product_id': 2, 'quantity': 2, 'unit_price': 3, 'status': 'pending'}], [{'product_id': 1, 'category_id': 7}, {'product_id': 2, 'category_id': 8}], [{'category_id': 7, 'category_name': 'Drinks'}, {'category_id': 8, 'category_name': 'Sides'}])
Output: [{'category_name': 'Drinks', 'total_sales': 12.5, 'average_sales_per_order': 12.5, 'completion_rate': 1}, {'category_name': 'Sides', 'total_sales': 6, 'average_sales_per_order': 6, 'completion_rate': 0}]
Hints
Hint 1
Build two dictionaries first: one from product id to category id and one from category id to category name. Then each order can be resolved in constant time.
Hint 2
Do not materialize a merged table. Keep, per category name, a running row count, a running sales total and a running count of completed rows.
Hint 3
Skip an order if either lookup fails. After the pass, derive both ratios by dividing by the row count, which is at least 1 for every group that exists, and sort by name.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is an inner join followed by a group-by aggregation. Both can be done with hash maps in a single pass over the orders.
- Build lookups. Create
product_id -> category_idfromproductsandcategory_id -> category_namefromcategories. For repeated keys, the later entry overwrites the earlier one, which gives the "last wins" rule. - Stream through the orders. For each order, look up its category id and then its category name. If either lookup fails, skip the row, which is the inner-join behaviour.
- Accumulate per name. For each category name keep
[row_count, sales_sum, completed_count]. Add 1 to the count, addquantity * unit_priceto the sum, and add 1 to the completed count when the status is exactly"completed". - Finalize. For each group,
total_salesis the sum,average_sales_per_orderis sum divided by count, andcompletion_rateis completed count divided by count. Emit the groups sorted by category name.
Why it is correct
- Rows with an unknown product or unknown category are dropped, exactly as an inner join would drop them.
- Grouping on the name rather than the id merges categories that share a name.
- Every surviving row increments the count, so both averages use the number of joined rows as the denominator, and non-completed rows still add to the sales total.
- A group is only created when a row is added to it, so the count is at least 1 and there is no division by zero.
- Sorting the items by name gives the required ascending order.
Complexity
With O orders, P products, C categories and G output groups:
- Time: O(P + C + O + G log G).
- Space: O(P + C + G), since no merged intermediate table is built.
Reference solution
from collections import defaultdict
from typing import Dict, List
def summarize_category_sales(orders: List[Dict], products: List[Dict], categories: List[Dict]) -> List[Dict]:
product_category = {row["product_id"]: row["category_id"] for row in products}
category_name = {row["category_id"]: row["category_name"] for row in categories}
# Per category name: [row_count, total_sales, completed_count]
totals = defaultdict(lambda: [0, 0.0, 0])
for order in orders:
product_id = order["product_id"]
if product_id not in product_category:
continue
category_id = product_category[product_id]
if category_id not in category_name:
continue
name = category_name[category_id]
sales = order["quantity"] * order["unit_price"]
aggregate = totals[name]
aggregate[0] += 1
aggregate[1] += sales
aggregate[2] += order["status"] == "completed"
return [
{
"category_name": name,
"total_sales": values[1],
"average_sales_per_order": values[1] / values[0],
"completion_rate": values[2] / values[0],
}
for name, values in sorted(totals.items())
]