Online store~25 min2s · 256 MBtarget O(n + m log n) time, O(n) spaceheaps
You work on an online store. A search shows the cheapest listings first, and a shopper reads only the first page. A catalogue can hold 200,000 listings, and a page needs at most 50,000 of the cheapest.
Your team lead asks: "Give me the m lowest prices, cheapest first." Sorting the whole catalogue is more work than the page needs. Build the heap yourself, with no library heap.
Write cheapest_listings(prices, m).
prices[i] is the price of listing i, in units.m is the number of prices needed. It is never more than the number of listings.m lowest prices, from the lowest to the highest. Equal prices appear as many times as they occur.Input: prices = [9, 4, 7, 1, 8, 2, 6], m = 3
Output: [1, 2, 4]The array is read as a tree: the children of position i are at 2i + 1 and 2i + 2. The table shows the heap after each step.
| Step | Heap array |
|---|---|
| start | 9, 4, 7, 1, 8, 2, 6 |
| sift down position 2 | 9, 4, 2, 1, 8, 7, 6 |
| sift down position 1 | 9, 1, 2, 4, 8, 7, 6 |
| sift down position 0 | 1, 4, 2, 9, 8, 7, 6 |
| take 1 | 2, 4, 6, 9, 8, 7 |
| take 2 | 4, 7, 6, 9, 8 |
| take 4 | 6, 7, 8, 9 |
Input: prices = [3, 3, 1, 2], m = 4
Output: [1, 2, 3, 3]Input: prices = [5], m = 1
Output: [5]1 ≤ len(prices) ≤ 200,000, and each price is from 1 to 10,000,000.1 ≤ m ≤ min(len(prices), 50,000)Picking the smallest by a scan, m times, costs up to 200,000 steps each time. For 20,000 picks that is 4 billion steps. A heap built over all 200,000 prices needs about 400,000 steps, and each pick then costs about 18 steps. Sorting the whole list would cost about 3,500,000 steps and gives more than the page needs.