Online store~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-164sorting
An online store lists its products by price. The merchandising team looks for the largest price gap between two neighbouring products when the catalogue is sorted by price. A gap shows where a new product would fill a hole in the range. The catalogue has up to 100,000 prices, and the team wants the answer without a full sort.
Write largest_price_gap(prices).
prices is a list of whole-number prices.0 when there are fewer than two prices.Input: prices = [10, 80, 25, 52, 41]
Output: 28The smallest is 10 and the largest is 80. Split that range into equal buckets, and keep only the smallest and largest price of each bucket.
Here the bucket size is 17, and there are 5 buckets.
| Bucket | Prices from | to | Smallest in it | Largest in it | Gap from the previous largest |
|---|---|---|---|---|---|
| 0 | 10 | 26 | 10 | 25 | none |
| 1 | 27 | 43 | 41 | 41 | 16 |
| 2 | 44 | 60 | 52 | 52 | 11 |
| 3 | 61 | 77 | empty | empty | skipped |
| 4 | 78 | 94 | 80 | 80 | 28 |
The largest gap always falls between two buckets, so the answer is 28.
Input: prices = [7]
Output: 0One price has no neighbour, so the answer is 0.
Input: prices = [5, 5, 5]
Output: 0Equal prices have gaps of 0, so the answer is 0.
0 ≤ prices.length ≤ 100,000 (products)0 ≤ prices[i] ≤ 10,000,000 (minor units)A comparison sort costs about n log n, which is 1.7 million steps at n = 100,000. That is fast enough, but the task asks for O(n), and the range of prices can be used to place each price in a bucket without comparing.