Most Common Item Pair Across Shopping Baskets
Arrays & HashingAuto-graded · 14 test casesLast 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]. Theuser_id,order_idandproduct_idvalues are integers.order_timeis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Walk through the line items and build a map from
order_idto the set of products in that order. Using a set removes repeated products within one order. - For each order, sort its distinct products and generate every 2-element combination. Because the list is sorted, each pair comes out as
(smaller, larger), so(a, b)and(b, a)collapse into one key. A product is never paired with itself. - Add one to a counter for each pair produced. Since each order yields a given pair at most once, the counter holds the number of distinct orders containing that pair.
- If the counter is empty, no order had two distinct products, so return
[]. - Otherwise find the maximum count and return the smallest pair (by tuple comparison) among those with that count.
Why it is correct
- Deduplicating per order guarantees that repeated line items cannot inflate a pair's count.
- Sorting before taking combinations gives each unordered pair exactly one representation.
- Grouping by
order_id(notuser_id) matches the "per order" definition. - Taking
minover the tied pairs matches the required lexicographic tie-break.
Complexity
- Time: O(N + sum of k_i^2), where N is the number of line items and k_i is the number of distinct products in order i. Sorting each order adds O(k_i log k_i).
- Space: O(N + P), where P is the number of distinct pairs seen.
Reference solution
from collections import Counter, defaultdict
from itertools import combinations
from typing import List
def most_common_pair_in_orders(line_items: List[List[object]]) -> List[int]:
products_by_order = defaultdict(set)
for row in line_items:
user_id, order_id, product_id, order_time = row
products_by_order[order_id].add(product_id)
counts = Counter()
for products in products_by_order.values():
counts.update(combinations(sorted(products), 2))
if not counts:
return []
best_count = max(counts.values())
return list(min(pair for pair, c in counts.items() if c == best_count))