Top Two Spending Categories per Shopper with Share of Spend
SQL & DataAuto-graded · 16 test casesLast updated
Aggregate line-item spend by shopper and category, rank with ties, keep the top two ranks, add spend share, and handle shoppers with no purchases.
Top Categories per Shopper
You are given four tables as lists of dictionaries: shoppers, purchases (orders), line items, and a product catalog. Build a report with each shopper's two highest-spend product categories, including ties, plus a list of shoppers whose spending is spread out.
Input tables
Every table is a list of dictionaries with these keys:
shoppers:id,namepurchases:id,customer_id(a shopper id),order_date(an ISOYYYY-MM-DDstring)line_items:id,order_id(a purchase id),product_id,qty,unit_pricecatalog:id(a product id),category,name
Aggregation
A line item counts only if its order_id matches a purchase and its product_id matches a catalog product. Skip every other line item. Each counted line item belongs to the purchase's customer_id and to the product's category.
For each (customer_id, category) pair, compute:
total_spend: the sum ofqty * unit_priceover its counted line items.earliest_order_date: the smallestorder_dateamong those line items. Compare the ISO strings directly.
Ranking
Within each customer, order the categories by total_spend descending, then earliest_order_date ascending. Assign ranks like SQL RANK():
- Categories with identical
(total_spend, earliest_order_date)share a rank. - The next distinct category gets rank = its 1-based position in the sorted order, so ranks can skip numbers after a tie.
Keep only categories with rank <= 2. Every category tied at rank 2 is kept, so a customer can have more than two rows. If several categories tie at rank 1, the next rank is 3, so only the tied rank-1 categories remain.
Share of spend
For each kept row, percent_of_total is total_spend divided by the customer's total spend over all their categories, not only the kept ones. If the customer's overall total is not greater than 0, percent_of_total is 0.
Shoppers without purchases
Every shopper in shoppers who has no counted line items (no purchases at all, or only purchases whose items were skipped) gets exactly one row:
category = None, total_spend = 0, earliest_order_date = None, rank_in_customer = None, percent_of_total = 0.
A customer id that appears in purchases but not in shoppers is still reported normally if it has counted line items.
Output
Return a dictionary with two keys:
"rows": a list of dictionaries with keyscustomer_id,category,total_spend,earliest_order_date,rank_in_customer,percent_of_total. Order the rows as follows:- Customers with counted line items come first, in order of the first appearance of any of their counted line items in
line_items. - Within a customer, rows go in ranked order (spend descending, then date ascending). Rows that tie completely stay in order of the first appearance of their
(customer, category)pair inline_items. - The no-purchase shoppers follow, in the order they appear in
shoppers.
- Customers with counted line items come first, in order of the first appearance of any of their counted line items in
"customer_ids_with_top_category_below_half": a sorted ascending list of customer ids whose rank-1 row haspercent_of_total < 0.5. Shoppers with no counted purchases have no rank-1 row and are never included.
Constraints
- All four tables may be empty.
- Ids are integers.
qtyis a non-negative integer.unit_priceis a non-negative number. - Dates are valid ISO strings, so lexicographic order equals chronological order.
- Table sizes are small enough for a single pass in memory, up to about 10^5 line items.
Examples
Example 1
Input: top_categories_by_shopper([{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Cara'}, {'id': 4, 'name': 'Dana'}], [{'id': 101, 'customer_id': 1, 'order_date': '2025-07-02'}, {'id': 102, 'customer_id': 1, 'order_date': '2025-07-15'}, {'id': 103, 'customer_id': 2, 'order_date': '2025-07-20'}, {'id': 104, 'customer_id': 2, 'order_date': '2025-07-21'}, {'id': 105, 'customer_id': 3, 'order_date': '2025-07-22'}], [{'id': 1001, 'order_id': 101, 'product_id': 201, 'qty': 2, 'unit_price': 10}, {'id': 1002, 'order_id': 101, 'product_id': 202, 'qty': 1, 'unit_price': 20}, {'id': 1003, 'order_id': 102, 'product_id': 201, 'qty': 1, 'unit_price': 10}, {'id': 1004, 'order_id': 102, 'product_id': 203, 'qty': 5, 'unit_price': 5}, {'id': 1005, 'order_id': 103, 'product_id': 202, 'qty': 2, 'unit_price': 20}, {'id': 1006, 'order_id': 104, 'product_id': 203, 'qty': 10, 'unit_price': 5}, {'id': 1007, 'order_id': 105, 'product_id': 204, 'qty': 1, 'unit_price': 100}], [{'id': 201, 'category': 'CatA', 'name': 'A'}, {'id': 202, 'category': 'CatA', 'name': 'B'}, {'id': 203, 'category': 'CatB', 'name': 'C'}, {'id': 204, 'category': 'CatC', 'name': 'D'}])
Output: {'rows': [{'customer_id': 1, 'category': 'CatA', 'total_spend': 50, 'earliest_order_date': '2025-07-02', 'rank_in_customer': 1, 'percent_of_total': 0.6666666666666666}, {'customer_id': 1, 'category': 'CatB', 'total_spend': 25, 'earliest_order_date': '2025-07-15', 'rank_in_customer': 2, 'percent_of_total': 0.3333333333333333}, {'customer_id': 2, 'category': 'CatB', 'total_spend': 50, 'earliest_order_date': '2025-07-21', 'rank_in_customer': 1, 'percent_of_total': 0.5555555555555556}, {'customer_id': 2, 'category': 'CatA', 'total_spend': 40, 'earliest_order_date': '2025-07-20', 'rank_in_customer': 2, 'percent_of_total': 0.4444444444444444}, {'customer_id': 3, 'category': 'CatC', 'total_spend': 100, 'earliest_order_date': '2025-07-22', 'rank_in_customer': 1, 'percent_of_total': 1}, {'customer_id': 4, 'category': None, 'total_spend': 0, 'earliest_order_date': None, 'rank_in_customer': None, 'percent_of_total': 0}], 'customer_ids_with_top_category_below_half': []}
Hints
Hint 1
Build two dictionaries first: product id to category, and purchase id to (customer_id, order_date). Skip line items that fail either lookup.
Hint 2
Accumulate the sum and the minimum date per (customer_id, category) in one pass. Also keep a per-customer grand total over all categories, since the share must not be computed from only the top two.
Hint 3
Sort each customer's categories by (-spend, date) and assign ranks as RANK() does, so tied entries share a rank and the next rank jumps to the position index plus one. Add no-purchase shoppers at the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has three stages: aggregate, rank, then add the shoppers with no purchases.
- Aggregate. Build a map from product id to category and a map from purchase id to
(customer_id, order_date). Scan the line items once. Skip any item whose purchase or product is unknown, which is the equivalent of inner joins. For each(customer, category)key, addqty * unit_priceto the running spend and keep the minimum date. A dictionary preserves first-appearance order, which gives the required output order and the stable tie order. - Rank. Group the aggregated entries by customer, and compute each customer's grand total over all categories before any filtering. Sort each customer's categories by
(-total_spend, earliest_order_date). Walk the sorted list and assign ranks asRANK()does: the rank stays the same while(spend, date)equals the previous entry's, and otherwise becomes the 1-based position. Emit only rows with rank <= 2, withpercent_of_total = spend / grand_total, or0if the grand total is not positive. - Fill in empty shoppers. Any shopper with no aggregated entries gets one placeholder row with
Nonevalues, spend 0, and share 0.
Finally, collect the share of each rank-1 row and return the customer ids whose share is below 0.5, sorted. Placeholder rows have no rank 1, so those shoppers are never listed.
Why it is correct
- Spend and earliest date are computed exactly per
(customer, category)from valid line items only. - The grand total comes from all categories, so shares are not inflated by the top-two filter.
- The rank rule reproduces
RANK(), including ties at rank 2 (all kept) and skipped ranks after ties. - Placeholder rows never enter the ranking, so they cannot receive a rank.
Complexity
Let N be the number of line items, G the number of (customer, category) groups, and S the number of shoppers.
- Time: O(N + G log G + S). The log factor comes from sorting categories within customers.
- Space: O(G + S).
Reference solution
from collections import defaultdict
from typing import Dict, List
def top_categories_by_shopper(shoppers: List[Dict], purchases: List[Dict],
line_items: List[Dict], catalog: List[Dict]) -> Dict:
category_of = {p['id']: p['category'] for p in catalog}
purchase_info = {o['id']: (o['customer_id'], o['order_date']) for o in purchases}
# Aggregate per (customer, category); dict keeps first-appearance order.
spend = {}
for item in line_items:
info = purchase_info.get(item['order_id'])
if info is None:
continue
cat = category_of.get(item['product_id'])
if cat is None:
continue
cid, date = info
key = (cid, cat)
amount = item['qty'] * item['unit_price']
if key not in spend:
spend[key] = {'total_spend': amount, 'earliest_order_date': date}
else:
spend[key]['total_spend'] += amount
if date < spend[key]['earliest_order_date']:
spend[key]['earliest_order_date'] = date
customer_total = defaultdict(float)
per_customer = {}
for (cid, cat), data in spend.items():
customer_total[cid] += data['total_spend']
per_customer.setdefault(cid, []).append({
'category': cat,
'total_spend': data['total_spend'],
'earliest_order_date': data['earliest_order_date'],
})
rows = []
for cid, cats in per_customer.items():
cats.sort(key=lambda x: (-x['total_spend'], x['earliest_order_date']))
total = customer_total[cid]
rank = 1
for i, c in enumerate(cats):
if i > 0:
prev = cats[i - 1]
if (c['total_spend'] != prev['total_spend'] or
c['earliest_order_date'] != prev['earliest_order_date']):
rank = i + 1
if rank <= 2:
rows.append({
'customer_id': cid,
'category': c['category'],
'total_spend': c['total_spend'],
'earliest_order_date': c['earliest_order_date'],
'rank_in_customer': rank,
'percent_of_total': c['total_spend'] / total if total > 0 else 0,
})
for s in shoppers:
if s['id'] not in per_customer:
rows.append({
'customer_id': s['id'],
'category': None,
'total_spend': 0,
'earliest_order_date': None,
'rank_in_customer': None,
'percent_of_total': 0,
})
top_share = {}
for r in rows:
if r['rank_in_customer'] == 1:
top_share[r['customer_id']] = r['percent_of_total']
below_half = sorted(cid for cid, pct in top_share.items() if pct < 0.5)
return {
'rows': rows,
'customer_ids_with_top_category_below_half': below_half,
}