Reconcile Orders with Product Catalog via Inner Join
SQL & DataAuto-graded · 13 test casesLast updated
Tests the ability to join two lists of dicts (orders + products) on a key, aggregate per customer, and return a cleaned, sorted summary.
Reconcile Orders with Product Catalog
You are given two tables represented as lists of dictionaries.
orders — each entry has:
| field | type | description |
|---|---|---|
order_id | int | unique order identifier |
customer_id | int | buyer's identifier |
product_id | int | product purchased |
quantity | int | units purchased (≥ 1) |
products — each entry has:
| field | type | description |
|---|---|---|
product_id | int | unique product identifier |
name | str | product name |
unit_price | float | price per unit |
category | str | product category |
Task
Perform an inner join on product_id (orders that reference a product_id not present in products are silently dropped, and products with no orders are ignored).
For each customer_id that has at least one matched order, compute:
total_spent: sum ofquantity × unit_priceacross all matched orders for that customer, rounded to 2 decimal places.order_count: number of matched orders for that customer.top_category: the category (fromproducts) in which the customer spent the most money. In case of a tie, choose the category that comes first alphabetically.
Return a list of dicts, one per customer, each with keys customer_id (int), total_spent (float), order_count (int), and top_category (str).
The list must be sorted by total_spent descending; if two customers have the same total_spent, sort by customer_id ascending.
Constraints
0 ≤ len(orders) ≤ 2 0000 ≤ len(products) ≤ 2 000product_idvalues inproductsare unique.order_idvalues inordersare unique.1 ≤ quantity ≤ 1 0000.0 < unit_price ≤ 10 000.0- If
ordersis empty or no order matches any product, return[].
Examples
Example 1
Input: reconcile_orders([{'order_id': 1, 'customer_id': 101, 'product_id': 10, 'quantity': 2}, {'order_id': 2, 'customer_id': 101, 'product_id': 20, 'quantity': 1}, {'order_id': 3, 'customer_id': 102, 'product_id': 10, 'quantity': 5}], [{'product_id': 10, 'name': 'Widget A', 'unit_price': 9.99, 'category': 'Gadgets'}, {'product_id': 20, 'name': 'Widget B', 'unit_price': 4.5, 'category': 'Gadgets'}, {'product_id': 30, 'name': 'Widget C', 'unit_price': 1, 'category': 'Supplies'}])
Output: [{'customer_id': 102, 'total_spent': 49.95, 'order_count': 1, 'top_category': 'Gadgets'}, {'customer_id': 101, 'total_spent': 24.48, 'order_count': 2, 'top_category': 'Gadgets'}]
Example 2
Input: reconcile_orders([{'order_id': 1, 'customer_id': 1, 'product_id': 5, 'quantity': 3}, {'order_id': 2, 'customer_id': 1, 'product_id': 6, 'quantity': 2}, {'order_id': 3, 'customer_id': 2, 'product_id': 5, 'quantity': 1}, {'order_id': 4, 'customer_id': 2, 'product_id': 99, 'quantity': 10}], [{'product_id': 5, 'name': 'Alpha', 'unit_price': 10, 'category': 'Electronics'}, {'product_id': 6, 'name': 'Beta', 'unit_price': 25, 'category': 'Furniture'}])
Output: [{'customer_id': 1, 'total_spent': 80, 'order_count': 2, 'top_category': 'Furniture'}, {'customer_id': 2, 'total_spent': 10, 'order_count': 1, 'top_category': 'Electronics'}]
Example 3
Input: reconcile_orders([], [{'product_id': 1, 'name': 'Solo', 'unit_price': 5, 'category': 'Misc'}])
Output: []
Hints
Hint 1
Build a dict keyed by product_id from the products list so lookups are O(1) when iterating over orders.
Hint 2
Use a nested dict keyed by customer_id, then category to accumulate spend per category, so finding top_category is a single max() call per customer.
Hint 3
Apply Python's round(value, 2) only at the very end when building the result dicts to avoid compounding rounding errors.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a classic hash-join + group-by aggregation pattern, mirroring SQL's INNER JOIN … GROUP BY customer_id.
Steps
-
Build a product lookup dict (
product_id → product row) — O(P) time, O(P) space, enabling O(1) lookup per order. -
Iterate over orders, skipping any whose
product_idis absent in the lookup (inner-join semantics). For each matched order:- Accumulate
quantity × unit_priceinto per-customer totals. - Increment per-customer order count.
- Accumulate spend per
(customer_id, category).
- Accumulate
-
Compute
top_categoryper customer: callmin(cat_spend, key=lambda c: (-cat_spend[c], c)), which picks the category with the largest spend and breaks ties alphabetically. -
Round
total_spentto 2 decimal places only at result-building time to avoid cascading rounding. -
Sort the result list by
(-total_spent, customer_id).
Correctness
- Dropping unmatched orders mirrors SQL INNER JOIN behaviour exactly.
- Accumulating floating-point spend in Python floats is fine given the problem's scale; rounding at the end keeps results stable.
- The composite sort key
(-total_spent, customer_id)satisfies the specified tie-break.
Complexity
| Time | Space | |
|---|---|---|
| Build product map | O(P) | O(P) |
| Process orders | O(N × C) worst-case where C = distinct categories per customer, typically O(N) | O(N) |
| Sort result | O(K log K) where K = distinct customers | O(K) |
| Overall | O(N + P + K log K) | O(N + P) |
For N, P ≤ 2 000 this is well within any practical limit.
from collections import defaultdict
def reconcile_orders(orders: list, products: list) -> list:
# Build product lookup
product_map = {p["product_id"]: p for p in products}
# Per customer: total_spent, order_count, category_spend
customer_total = defaultdict(float)
customer_count = defaultdict(int)
customer_cat = defaultdict(lambda: defaultdict(float))
for order in orders:
pid = order["product_id"]
if pid not in product_map:
continue
product = product_map[pid]
cid = order["customer_id"]
spend = order["quantity"] * product["unit_price"]
cat = product["category"]
customer_total[cid] += spend
customer_count[cid] += 1
customer_cat[cid][cat] += spend
result = []
for cid in customer_total:
# top category: most spend, alphabetical tie-break
cat_spend = customer_cat[cid]
top_cat = min(cat_spend, key=lambda c: (-cat_spend[c], c))
result.append({
"customer_id": cid,
"total_spent": round(customer_total[cid], 2),
"order_count": customer_count[cid],
"top_category": top_cat,
})
result.sort(key=lambda x: (-x["total_spent"], x["customer_id"]))
return result