Highest Revenue Product per Category with Returns
SQL & DataAuto-graded · 17 test casesLast updated
Tests data aggregation, join logic, net-revenue calculation accounting for returns, and ranking with tie-breaking.
You are given four tables representing an e-commerce system: orders, order_items, products, and returns. Your task is to identify the single product in each category that generated the highest net revenue during a specific 7-day period (2025-08-26 through 2025-09-01, inclusive).
Tables
orders
order_id: unique order identifieruser_id: customer identifierorder_date: date the order was placed (string formatYYYY-MM-DD)
order_items
order_id: references ordersproduct_id: references productsqty: quantity ordered (positive integer)
products
product_id: unique product identifiername: product namecategory: product categoryprice_usd: unit price in dollars (positive integer)
returns
return_id: unique return identifierorder_id: references ordersproduct_id: references productsqty_returned: quantity returned (positive integer)return_date: date the return was processed (string formatYYYY-MM-DD)
Calculation Rules
-
Order window: Only consider orders where
order_datefalls between 2025-08-26 and 2025-09-01 (inclusive). -
Net units: For each product, calculate total units sold minus total units returned:
- Sum all
qtyfromorder_itemsfor orders in the date window - Subtract all
qty_returnedfromreturnswhere both the associated order is in the window AND thereturn_dateis also in the window - Returns are matched by both
order_idandproduct_id
- Sum all
-
Net revenue: Multiply net units by the product's
price_usd. -
Ranking: Within each category, select the product with the highest net revenue. If multiple products tie on net revenue:
- Break ties by choosing the product with higher net units
- If still tied, choose the product with the lexicographically smallest
product_id
Output
Return a list of dictionaries, one per category, sorted by category name. Each dictionary must contain:
category: the category nameproduct_id: the winning product identifiernet_units: the net units sold for that productnet_revenue_usd: the net revenue for that product
Categories with no sales during the window should not appear in the output.
Constraints
- 1 ≤ number of orders ≤ 10,000
- 1 ≤ number of order_items ≤ 50,000
- 1 ≤ number of products ≤ 1,000
- 0 ≤ number of returns ≤ 10,000
- All dates are valid strings in
YYYY-MM-DDformat - All quantities and prices are positive integers
- A product may appear multiple times in the same order (multiple line items)
- A return may reference an order outside the date window
- Net units for a product will always be non-negative after accounting for returns
Examples
Example 1
Input: highest_revenue_per_category([{'order_id': 'O1', 'user_id': 1, 'order_date': '2025-08-26'}, {'order_id': 'O2', 'user_id': 2, 'order_date': '2025-08-27'}, {'order_id': 'O3', 'user_id': 1, 'order_date': '2025-08-30'}, {'order_id': 'O4', 'user_id': 3, 'order_date': '2025-08-31'}, {'order_id': 'O5', 'user_id': 4, 'order_date': '2025-09-01'}], [{'order_id': 'O1', 'product_id': 'P1', 'qty': 1}, {'order_id': 'O1', 'product_id': 'P2', 'qty': 2}, {'order_id': 'O2', 'product_id': 'P3', 'qty': 1}, {'order_id': 'O3', 'product_id': 'P3', 'qty': 1}, {'order_id': 'O3', 'product_id': 'P4', 'qty': 3}, {'order_id': 'O4', 'product_id': 'P2', 'qty': 1}, {'order_id': 'O5', 'product_id': 'P1', 'qty': 1}], [{'product_id': 'P1', 'name': 'Desk', 'category': 'Furniture', 'price_usd': 200}, {'product_id': 'P2', 'name': 'Chair', 'category': 'Furniture', 'price_usd': 120}, {'product_id': 'P3', 'name': 'Monitor', 'category': 'Electronics', 'price_usd': 300}, {'product_id': 'P4', 'name': 'Keyboard', 'category': 'Electronics', 'price_usd': 80}], [{'return_id': 'R1', 'order_id': 'O1', 'product_id': 'P2', 'qty_returned': 1, 'return_date': '2025-08-31'}, {'return_id': 'R2', 'order_id': 'O3', 'product_id': 'P4', 'qty_returned': 1, 'return_date': '2025-09-01'}])
Output: [{'category': 'Electronics', 'product_id': 'P3', 'net_units': 2, 'net_revenue_usd': 600}, {'category': 'Furniture', 'product_id': 'P1', 'net_units': 2, 'net_revenue_usd': 400}]
Hints
Hint 1
Aggregate order items and returns separately to the same granularity (order_id, product_id) before joining to avoid double-counting due to join fan-out.
Hint 2
Returns only reduce net units if both the original order date AND the return date fall within the 7-day window.
Hint 3
Use a three-level sort key (revenue descending, units descending, product_id ascending) to ensure deterministic tie-breaking within each category.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is correctly computing net units and net revenue while avoiding double-counting caused by joins between tables with different granularities.
Step-by-step strategy:
-
Filter orders by date window: Build a lookup of orders whose
order_datefalls between 2025-08-26 and 2025-09-01. -
Aggregate sold quantities: For each
(order_id, product_id)pair fromorder_itemswhere the order is in the window, sum the quantities sold. This gives us one total per combination. -
Aggregate returned quantities: For each
(order_id, product_id)pair fromreturnswhere both the order is in the window AND thereturn_dateis also in the window, sum the quantities returned. Again, one total per combination. -
Compute net units per product: Iterate through the sold quantities. For each
(order_id, product_id), subtract the corresponding returned quantity (defaulting to 0 if no returns exist). Accumulate these net values byproduct_id. -
Calculate net revenue: Multiply each product's net units by its unit price from the
productstable. -
Rank within categories: Group products by category. For each category, select the product with the maximum net revenue. Ties are broken first by net units (higher wins), then by
product_id(lexicographically smaller wins). -
Return results: Sort output by category name.
Why this works:
By aggregating sold and returned quantities to the same grain (order_id, product_id) before combining them, we ensure each transaction is counted exactly once. The left-join semantics (returns default to 0) prevent phantom subtractions for products with no returns.
Time Complexity: O(O + I + R + P + C log C), where O, I, R, P are the sizes of orders, order_items, returns, and products respectively, and C is the number of categories. The sorting of categories dominates when C is large.
Space Complexity: O(O + I + P) for the hash tables storing order lookups, aggregated quantities, and product information.
from collections import defaultdict
from typing import Dict, List
def highest_revenue_per_category(orders, order_items, products, returns):
window_start, window_end = "2025-08-26", "2025-09-01"
# Build a set of order IDs within the date window
orders_in_window = {
order["order_id"]: order["order_date"]
for order in orders
if window_start <= order["order_date"] <= window_end
}
# Index products by product_id for fast lookup
product_lookup = {product["product_id"]: product for product in products}
# Aggregate quantities sold per (order_id, product_id) for orders in window
sold_by_key = defaultdict(int)
for item in order_items:
oid = item["order_id"]
if oid in orders_in_window:
sold_by_key[(oid, item["product_id"])] += item["qty"]
# Aggregate quantities returned per (order_id, product_id) where both dates are in window
returned_by_key = defaultdict(int)
for ret in returns:
oid = ret["order_id"]
if oid in orders_in_window and window_start <= ret["return_date"] <= window_end:
returned_by_key[(oid, ret["product_id"])] += ret["qty_returned"]
# Calculate net units per product
net_units_by_product = defaultdict(int)
for (oid, pid), qty_sold in sold_by_key.items():
qty_ret = returned_by_key[(oid, pid)]
net_units_by_product[pid] += qty_sold - qty_ret
# Group products by category and compute net revenue
category_candidates = defaultdict(list)
for pid, net_units in net_units_by_product.items():
prod = product_lookup[pid]
net_rev = net_units * prod["price_usd"]
category_candidates[prod["category"]].append((net_rev, net_units, pid))
# Select the top product per category using tie-breaking rules
result = []
for cat in sorted(category_candidates):
# Sort by: revenue desc, units desc, product_id asc
net_rev, net_units, pid = min(
category_candidates[cat],
key=lambda x: (-x[0], -x[1], x[2])
)
result.append({
"category": cat,
"product_id": pid,
"net_units": net_units,
"net_revenue_usd": net_rev
})
return result