Cheapest Top-Rated Purchase per Category
SQL & DataAuto-graded · 23 test casesLast updated
Join two tables as lists, filter on a strict rating threshold with missing values, and compute a per-group minimum with a default of 0 and sorted output.
An online store keeps its catalog and its sales history as two lists of rows.
catalogrows look like[item_id, item_name, group_name].ordersrows look like[order_id, item_id, amount, rating].
The rating of an order is either an integer or None when the buyer left no rating. The amount is a number.
For every distinct group_name that appears in catalog, work out a single figure:
- Look only at orders whose
ratingis present and strictly greater than 4. A missing rating never qualifies, and a rating of exactly 4 does not qualify. - An order belongs to a group through its
item_id. Orders whoseitem_idis not incatalogare ignored. - The figure for the group is the smallest
amountamong its qualifying orders. Only qualifying orders take part in the minimum; a cheaper order with a low rating must not be used. - If a group has no qualifying order (including a group with no orders at all), its figure is
0.
Return a list of dictionaries, one per group, each of the form {"category": group_name, "price": figure}. The list must be sorted by category in ascending order.
This is the Python equivalent of a LEFT JOIN from the catalog to the orders with the rating filter in the join condition, followed by MIN with a COALESCE(..., 0) and ORDER BY category.
Constraints
- Each group name appears in the result exactly once, even if several items share it.
- A qualifying order with amount
0is legitimate and yields0as its genuine minimum. - Rating comparison is strict:
rating > 4. - The returned
pricevalues keep the numeric type of the input amounts (or the integer0for the default). - Input lists may be empty; an empty catalog gives an empty list.
Examples
Example 1
Input: cheapest_top_rated_by_group([[1, 'iPhone 14', 'Apple'], [2, 'MacBook Air', 'Apple'], [3, 'Banana Phone', 'Banana'], [4, 'Pear X', 'Pear'], [5, 'Orange Z', 'Orange']], [[10, 1, 999, 5], [11, 1, 1099, 3], [12, 2, 1299, 4], [13, 3, 49, 5], [14, 3, 39, 2], [15, 4, 199, 4], [16, 4, 179, None], [17, 5, 299, None]])
Output: [{'category': 'Apple', 'price': 999}, {'category': 'Banana', 'price': 49}, {'category': 'Orange', 'price': 0}, {'category': 'Pear', 'price': 0}]
Hints
Hint 1
Start the result with every group from the catalog set to 0, so groups without any qualifying order still appear.
Hint 2
Build a lookup from item id to group name, then scan the orders once, skipping those with a missing rating, a rating not above 4, or an unknown item id.
Hint 3
Do not decide whether a minimum has been set by checking if the current value is 0; track which groups already have a qualifying order, since the real minimum could itself be 0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a filtered aggregation that must keep every group, which is what a LEFT JOIN with the filter in the ON clause, MIN, and COALESCE(..., 0) would do in SQL. In Python we mirror it directly:
- Build a dictionary mapping each
item_idto its group name. - Create a result dictionary with every group from the catalog initialised to
0. This plays the role of the left join plus the default value. - Keep a set of groups that already have a qualifying order.
- Scan the orders once. Skip an order if its rating is
None, is not strictly greater than 4, or itsitem_idis not in the catalog. Otherwise, if the group has no minimum yet or the amount is smaller than the current one, store the amount and mark the group. - Output the groups in sorted order as
{"category": ..., "price": ...}dictionaries.
Why it is correct
- Every group from the catalog is present from the start, so groups with no orders or no qualifying orders correctly report
0. - Only orders passing the rating filter can change a group's value, so the minimum is taken over qualifying orders only. A cheaper low-rated order never interferes.
- The
has_minset makes the first qualifying order always replace the placeholder0. Comparing against the placeholder directly would leave every group at0, and would also be ambiguous if a real minimum were0. Noneis checked explicitly because comparingNone > 4raises an error in Python 3, whereas SQL treats it as not true.- Sorting the group names gives the required deterministic order.
Complexity
With P catalog rows, Q order rows and C groups: time O(P + Q + C log C), space O(P + C).
Reference solution
from typing import List, Dict
def cheapest_top_rated_by_group(catalog: List[List], orders: List[List]) -> List[Dict]:
item_group = {row[0]: row[2] for row in catalog}
best = {row[2]: 0 for row in catalog}
has_min = set()
for order in orders:
order_id, item_id, amount, rating = order
if rating is not None and rating > 4 and item_id in item_group:
group = item_group[item_id]
if group not in has_min or amount < best[group]:
best[group] = amount
has_min.add(group)
return [
{"category": group, "price": best[group]}
for group in sorted(best)
]