Ad platform~20 min2s · 256 MBtarget O(n log n) time, O(log n) spacesorting
An ad platform settles a batch of bids. Bids are rounded to price tiers before settlement, so many bids in a batch are equal. The job has memory for the batch and little more, so it must sort the bids in place.
The job uses quick sort: pick a pivot, split the batch around it, and sort each side. A batch with many equal bids is the case that breaks a careless version.
Write sort_bids(bids).
bids[i] is the bid of the i-th entry, in the order they arrived.Input: bids = [5, 3, 5, 1, 5, 3, 2]
Output: [1, 2, 3, 3, 5, 5, 5]Take 3 as the pivot. One three-way pass puts the smaller bids first, the bids equal to 3 in the middle, and the larger bids last. The table shows the pass. The index lt is where the next smaller bid goes, i is the bid being looked at, and gt is where the next larger bid goes.
| Step | Bid at i | What happens | List after | lt | i | gt |
|---|---|---|---|---|---|---|
| 1 | 5 | larger: swap to the back | [2, 3, 5, 1, 5, 3, 5] | 0 | 0 | 5 |
| 2 | 2 | smaller: swap to the front | [2, 3, 5, 1, 5, 3, 5] | 1 | 1 | 5 |
| 3 | 3 | equal: leave it | [2, 3, 5, 1, 5, 3, 5] | 1 | 2 | 5 |
| 4 | 5 | larger: swap to the back | [2, 3, 3, 1, 5, 5, 5] | 1 | 2 | 4 |
| 5 | 3 | equal: leave it | [2, 3, 3, 1, 5, 5, 5] | 1 | 3 | 4 |
| 6 | 1 | smaller: swap to the front | [2, 1, 3, 3, 5, 5, 5] | 2 | 4 | 4 |
| 7 | 5 | larger: swap to the back | [2, 1, 3, 3, 5, 5, 5] | 2 | 4 | 3 |
Now i has passed gt. Places 0 to 1 hold values smaller than 3, and places 2 to 3 hold the 3s, which are final. Places 4 to 6 hold larger values. Sorting the two outer parts gives the answer.
Input: bids = [4, 4, 4, 4]
Output: [4, 4, 4, 4]All bids are equal, so one pass leaves them all in the middle part.
Input: bids = [9, 1]
Output: [1, 9]0 ≤ bids.length ≤ 50,000 (bids)0 ≤ bids[i] ≤ 1,000,000,000 (units)Insertion sort costs about n × n / 4 shifts, which is 6 × 10^8 at n = 50,000. Quick sort costs about n log n, roughly 800,000 steps. A two-way partition on a batch with only 10 different bids costs about n × n / 20, which is 1.25 × 10^8 comparisons.