Online store~25 min2s · 256 MBtarget O(total + p log p) time, O(p) spacehashing · map-design
An online shop shows "customers also bought" on a product page. The shop has the baskets of past orders. Each basket lists the products of one order, and no product appears twice in a basket.
For a product, the shop looks at the baskets that hold it, and counts how often each other product is in them. It shows the products that most often share a basket with it.
Write bought_together(baskets, target, k).
baskets[i] is the list of distinct product ids in order i.p other than target, count the baskets that hold both target and p.k products in that ranking. If fewer than k products qualify, return all of them.Input: baskets = [[1, 2, 3], [1, 2, 4], [2, 3, 5], [1, 3], [1, 2, 3, 6], [7, 8]], target = 1, k = 3
Output: [2, 3, 4]The trace counts the baskets that hold product 1 together with each other product.
| Product | Baskets that hold it and product 1 | Count |
|---|---|---|
| 2 | basket 0, basket 1, basket 4 | 3 |
| 3 | basket 0, basket 3, basket 4 | 3 |
| 4 | basket 1 | 1 |
| 6 | basket 4 | 1 |
Products 2 and 3 are each in 3 baskets with product 1. Products 4 and 6 are in 1 basket each, and 4 wins the tie with the smaller id. Products 5, 7 and 8 never share a basket with product 1.
Input: baskets = [[5, 6], [6, 7]], target = 9, k = 2
Output: []Product 9 is in no basket, so no product is bought with it. The output is empty.
Input: baskets = [[3], [3, 4]], target = 3, k = 5
Output: [4]Only product 4 shares a basket with product 3, and one basket holds product 3 alone. The output has one product, even though k is 5.
1 ≤ baskets.length ≤ 20,000; each basket has 1 to 20 distinct product ids1 ≤ product ids, target ≤ 10,000,0001 ≤ k ≤ 100There are at most 4 × 10^5 product entries in all. For every product, scanning every basket costs up to 4 × 10^5 × 2 × 10^4 = 8 × 10^9 steps. One pass over the baskets with a map of counts costs about 4 × 10^5 steps. Ranking the products costs a sort.