Online store~18 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting
You work on an online shop. A category page lists items, each with a price and a customer rating. The page groups prices into bands of equal width. With a band of 50, an item at 49 and an item at 31 count as the same price.
Your team lead asks: "In which order should the page show the items?" Cheaper bands come first. Inside a band, higher ratings come first, and equal ratings keep their original order. A page can have 100,000 items.
Write shelf_order(prices, ratings, band).
prices[i] and ratings[i] describe item i, counting from 0.i is prices[i] // band.Input: prices = [120, 95, 130, 80, 99], ratings = [4, 5, 3, 5, 4], band = 50
Output: [1, 3, 4, 0, 2]Work out each band, then sort by band, then by rating from high to low, then by item number.
| Shelf position by item | Price | Band | Rating |
|---|---|---|---|
| item 1 | 95 | 1 | 5 |
| item 3 | 80 | 1 | 5 |
| item 4 | 99 | 1 | 4 |
| item 0 | 120 | 2 | 4 |
| item 2 | 130 | 2 | 3 |
Items 1, 3 and 4 are in band 1, and items 0 and 2 are in band 2.
Input: prices = [30, 30, 30], ratings = [1, 1, 1], band = 10
Output: [0, 1, 2]Everything ties, so the items keep their original order.
Input: prices = [49, 50], ratings = [1, 5], band = 50
Output: [0, 1]Price 49 is in band 0 and price 50 is in band 1, so item 0 comes first even with the lower rating.
1 ≤ len(prices) = len(ratings) ≤ 100,0000 ≤ prices[i] ≤ 1,000,0000 ≤ ratings[i] ≤ 1,0001 ≤ band ≤ 1,000,000Placing the items one by one into the best position, as a selection sort does, takes about 5 billion comparisons for 100,000 items. That is too slow for a 2-second limit. A comparison sort makes about 1.7 million comparisons, so we need to sort once with a rule that covers all three keys.