KatInterview

Cheapest Top-Rated Purchase per Category

SQL & DataAuto-graded · 23 test cases
MediumAuto-gradedSQL & Dataaggregationleft-joinnull-handling

Last 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.

  • catalog rows look like [item_id, item_name, group_name].
  • orders rows 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 rating is 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 whose item_id is not in catalog are ignored.
  • The figure for the group is the smallest amount among 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 0 is legitimate and yields 0 as its genuine minimum.
  • Rating comparison is strict: rating > 4.
  • The returned price values keep the numeric type of the input amounts (or the integer 0 for 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.