Online store~25 min2s · 256 MBtarget O(n log n) time, O(n) spacecomplexity · sorting
An online store sorts its price list with a quick sort. The pivot is always the first price. Every other price is compared with the pivot once, and goes to the list of cheaper prices or the list of dearer prices, keeping its order. Each list is then sorted the same way.
The catalogue export often arrives already sorted. The team wants the number of comparisons for any list, without running the sort. You will count them exactly.
Write count_quicksort_comparisons(prices).
prices holds distinct prices. The sort picks prices[0] as the pivot of a list of two or more prices.Input: prices = [4, 2, 6, 1, 3, 5, 7]
Output: 10The first price, 4, splits the other six into [2, 1, 3] and [6, 5, 7]. Each of those splits again.
| List | Pivot | Comparisons |
|---|---|---|
| [4, 2, 6, 1, 3, 5, 7] | 4 | 6 |
| [2, 1, 3] | 2 | 2 |
| [6, 5, 7] | 6 | 2 |
| the four lists of one price | none | 0 |
The total is 10.
Input: prices = [1, 2, 3, 4, 5]
Output: 10Each pivot is the smallest price of its list, so one list is empty and the other holds all the rest. The comparisons are 4 + 3 + 2 + 1 = 10.
Input: prices = [9]
Output: 0A list of one price needs no comparison: 0.
0 ≤ prices.length ≤ 100,000 (products)1 ≤ prices[i] ≤ 10,000,000, all distinct (prices in minor units)Running the sort on a sorted list costs about n × n / 2 = 5 × 10^9 comparisons, far beyond a second. The count can pass 2 × 10^9, so use 64-bit integers. Find the count from the structure of the input instead of running the sort.