KatInterview

Most Common Item Pair Across Shopping Baskets

Arrays & HashingAuto-graded · 14 test cases
MediumAuto-gradedArrays & Hashinghash-mapcombinationscounting

Last updated

Find the two products that appear together in the most orders, handling duplicate lines, mirrored pairs, ties, and orders with fewer than two distinct products.

Most Common Item Pair Across Shopping Baskets

You are given a log of purchase line items. Each line item is a list of four values:

[user_id, order_id, product_id, order_time]

An order may span several line items that share the same order_id. Two different products are said to be bought together in an order if both appear among that order's line items.

Return the pair of products that is bought together in the largest number of distinct orders.

Rules

  • A pair is unordered: (23, 45) and (45, 23) are the same pair. Report it with the smaller product id first.
  • Within a single order, a product that appears on several line items counts only once. A pair never consists of a product with itself.
  • Each order contributes at most one count to any given pair. Counting is per order, not per user, so a user who buys the same pair in several orders adds one count for each order.
  • If several pairs share the highest count, return the one that is smallest in lexicographic order, comparing the first product id and then the second.
  • If no order contains at least two distinct products (including when the input is empty), return an empty list.

Input

  • transactions: a list of line items [user_id, order_id, product_id, order_time]. The user_id, order_id and product_id values are integers. order_time is a date string, which is not needed to solve the task.

Output

A list [p1, p2] with p1 < p2, or [] if there is no valid pair.

Constraints

  • 0 <= len(transactions) <= 10^5
  • Each line item has exactly four values.
  • Product ids and order ids are integers.
  • The number of distinct products in any single order is small enough that listing all pairs within that order is feasible.

Examples

Example 1

Input: most_common_pair_in_orders([[101, 5001, 23, '2023-09-01'], [101, 5001, 45, '2023-09-01'], [102, 5002, 23, '2023-09-01'], [103, 5003, 67, '2023-09-02'], [103, 5003, 45, '2023-09-02']])

Output: [23, 45]

Hints

Hint 1

Group the line items by order id first, and keep only the distinct products of each order, for example in a set.

Hint 2

For each order, sort its distinct products and generate all 2-element combinations. Sorting gives every unordered pair one canonical form.

Hint 3

Tally the pairs in a counter, take the maximum count, and among pairs with that count pick the smallest tuple. Return an empty list if the counter is empty.