Reconcile Sales Orders with Product Catalog
SQL & DataAuto-graded · 13 test casesLast updated
Tests joining two lists of dicts (orders + products) on a key, then aggregating revenue and applying data-cleaning rules.
Reconcile Sales Orders with Product Catalog
You are given two tables represented as lists of dictionaries:
orders — each dict has:
| Field | Type | Description |
|---|---|---|
order_id | str | Unique order identifier |
product_id | str | References a product |
quantity | int | Units ordered (≥ 1) |
discount_pct | float | Discount percentage in [0.0, 100.0) |
products — each dict has:
| Field | Type | Description |
|---|---|---|
product_id | str | Unique product identifier |
category | str | Product category name |
unit_price | float | Price per unit (> 0) |
Task
Perform an inner join on product_id, then compute the net revenue for each order:
net_revenue = quantity × unit_price × (1 - discount_pct / 100)
Return a list of dicts, one per category, with the following fields:
| Field | Type | Description |
|---|---|---|
category | str | Category name |
total_revenue | float | Sum of net revenue for all matched orders in this category, rounded to 2 decimal places |
order_count | int | Number of matched orders in this category |
avg_discount_pct | float | Mean discount_pct across matched orders in this category, rounded to 2 decimal places |
Data-cleaning rules
- Unmatched orders (no product with that
product_id) are silently dropped — they do not appear in any category. - If
unit_price≤ 0 orquantity≤ 0 for a matched row, treat that row'snet_revenueas 0.0 (but still count the order and include itsdiscount_pctin the average). - If the products table contains duplicate
product_ids, use the last occurrence (by list position).
Output ordering
Sort the result list by total_revenue descending. Break ties alphabetically by category ascending.
Constraints
0 ≤ len(orders) ≤ 20000 ≤ len(products) ≤ 2000product_idandcategoryare non-empty strings.discount_pct∈ [0.0, 100.0)unit_price> 0 in well-formed data (but see cleaning rule 2).- Returns
[]when no orders survive the inner join.
Examples
Example 1
Input: reconcile_orders([{'order_id': 'O1', 'product_id': 'P1', 'quantity': 2, 'discount_pct': 10}, {'order_id': 'O2', 'product_id': 'P2', 'quantity': 1, 'discount_pct': 0}, {'order_id': 'O3', 'product_id': 'P3', 'quantity': 5, 'discount_pct': 20}], [{'product_id': 'P1', 'category': 'Electronics', 'unit_price': 100}, {'product_id': 'P2', 'category': 'Books', 'unit_price': 15}, {'product_id': 'P3', 'category': 'Electronics', 'unit_price': 40}])
Output: [{'category': 'Electronics', 'total_revenue': 340, 'order_count': 2, 'avg_discount_pct': 15}, {'category': 'Books', 'total_revenue': 15, 'order_count': 1, 'avg_discount_pct': 0}]
Example 2
Input: reconcile_orders([{'order_id': 'O1', 'product_id': 'GHOST', 'quantity': 3, 'discount_pct': 5}], [{'product_id': 'P1', 'category': 'Toys', 'unit_price': 9.99}])
Output: []
Example 3
Input: reconcile_orders([{'order_id': 'O1', 'product_id': 'P1', 'quantity': 4, 'discount_pct': 25}, {'order_id': 'O2', 'product_id': 'P1', 'quantity': 2, 'discount_pct': 50}], [{'product_id': 'P1', 'category': 'Sports', 'unit_price': 50}, {'product_id': 'P1', 'category': 'Outdoors', 'unit_price': 80}])
Output: [{'category': 'Outdoors', 'total_revenue': 320, 'order_count': 2, 'avg_discount_pct': 37.5}]
Hints
Hint 1
Build a dict from the products list keyed by product_id (last occurrence wins) before iterating over orders — this gives O(1) lookups.
Hint 2
Use a second dict keyed by category to accumulate total_revenue, order_count, and the sum of discount_pct, then convert to a list at the end.
Hint 3
Apply the data-cleaning check (quantity ≤ 0 or unit_price ≤ 0) before adding to total_revenue, but always increment order_count and add to the discount sum.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a classical hash-join + grouped aggregation pattern, equivalent to SQL:
SELECT
p.category,
ROUND(SUM(o.quantity * p.unit_price * (1 - o.discount_pct/100)), 2) AS total_revenue,
COUNT(*) AS order_count,
ROUND(AVG(o.discount_pct), 2) AS avg_discount_pct
FROM orders o
JOIN products p USING (product_id)
GROUP BY p.category
ORDER BY total_revenue DESC, category ASC;
Steps
-
Build a product lookup dict (
product_id → product row) in one pass overproducts. Because we iterate in order and overwrite on duplicate keys, the last occurrence survives naturally. -
Iterate over
orders, skipping any whoseproduct_idis absent in the lookup (inner join / drop unmatched). For each surviving order:- Compute
net_revenue = quantity × unit_price × (1 − discount_pct/100), clamping to 0.0 ifquantity ≤ 0orunit_price ≤ 0. - Accumulate
total_revenue,order_count, anddiscount_suminto a per-category dict.
- Compute
-
Convert the accumulator to the output list, computing
avg_discount_pct = discount_sum / order_countand rounding both floats to 2 decimal places. -
Sort by
(-total_revenue, category)for the required tie-break.
Correctness
- Duplicate product ids: iterating once and overwriting ensures
O(P)time and the last-wins semantics. - Cleaning rule 2: we zero out revenue but still count the order — the count and average-discount accumulation is unconditional.
- Rounding happens only at output time, avoiding accumulated floating-point drift.
Complexity
| Time | O(P + O + C log C) where P = |products|, O = |orders|, C = |categories| |
| Space | O(P + C) |
Both are at most O(2000) in the given constraints.
def reconcile_orders(orders: list, products: list) -> list:
# Build product lookup: last occurrence wins for duplicate product_ids
product_map = {}
for p in products:
product_map[p["product_id"]] = p
# Accumulate per-category stats
cat_stats = {}
for order in orders:
pid = order["product_id"]
if pid not in product_map:
continue # unmatched order — drop silently
product = product_map[pid]
category = product["category"]
quantity = order["quantity"]
unit_price = product["unit_price"]
discount_pct = order["discount_pct"]
# Data-cleaning rule 2
if quantity <= 0 or unit_price <= 0:
net_revenue = 0.0
else:
net_revenue = quantity * unit_price * (1 - discount_pct / 100)
if category not in cat_stats:
cat_stats[category] = {"total_revenue": 0.0, "order_count": 0, "discount_sum": 0.0}
cat_stats[category]["total_revenue"] += net_revenue
cat_stats[category]["order_count"] += 1
cat_stats[category]["discount_sum"] += discount_pct
# Build result list
result = []
for category, stats in cat_stats.items():
avg_discount = stats["discount_sum"] / stats["order_count"]
result.append({
"category": category,
"total_revenue": round(stats["total_revenue"], 2),
"order_count": stats["order_count"],
"avg_discount_pct": round(avg_discount, 2),
})
# Sort: total_revenue desc, category asc as tie-break
result.sort(key=lambda x: (-x["total_revenue"], x["category"]))
return result