Ad platform~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-2161three-way-partition · two-pointers
An ad platform runs an auction for each ad slot. Every auction has a reserve price: the lowest bid the slot will accept. For quality checks, a review screen groups the bids of one auction around the reserve. Bids below it come first, then bids equal to it, then bids above it.
Reviewers read each group from top to bottom as a timeline. So inside a group, the bids must stay in the order they arrived. The screen groups the bids; it does not sort them by amount.
Write partition_bids(bids, reserve).
bids[i] is the amount of the bid that arrived in position i, in whole units. Amounts can repeat.reserve is the auction's reserve price, in the same units.reserve first, then every bid equal to reserve, then every bid above it.Input: bids = [30, 12, 25, 40, 8, 25, 15], reserve = 25
Output: [12, 8, 15, 25, 25, 30, 40]First count the groups: 3 bids are below 25 and 2 are equal to it. So the below group starts at slot 0, the equal group at slot 3 and the above group at slot 5.
| i | bids[i] | Group | Written to slot | Next free slot: below, equal, above | Output after |
|---|---|---|---|---|---|
| 0 | 30 | above | 5 | 0, 3, 6 | _, _, _, _, _, 30, _ |
| 1 | 12 | below | 0 | 1, 3, 6 | 12, _, _, _, _, 30, _ |
| 2 | 25 | equal | 3 | 1, 4, 6 | 12, _, _, 25, _, 30, _ |
| 3 | 40 | above | 6 | 1, 4, 7 | 12, _, _, 25, _, 30, 40 |
| 4 | 8 | below | 1 | 2, 4, 7 | 12, 8, _, 25, _, 30, 40 |
| 5 | 25 | equal | 4 | 2, 5, 7 | 12, 8, _, 25, 25, 30, 40 |
| 6 | 15 | below | 2 | 3, 5, 7 | 12, 8, 15, 25, 25, 30, 40 |
The bid of 12 arrived before the bid of 8, so it stays before it.
Input: bids = [50, 20, 70, 10], reserve = 40
Output: [20, 10, 50, 70]No bid equals the reserve, so the equal group is empty.
Input: bids = [9, 7, 8], reserve = 5
Output: [9, 7, 8]Every bid is above the reserve, so nothing moves. The bids stay in arrival order; they are not sorted.
1 ≤ bids.length ≤ 10^51 ≤ bids[i] ≤ 10^91 ≤ reserve ≤ 10^9Moving bids one slot at a time, as an insertion sort does, can take about 3.3 × 10^9 swaps at this size. Aim for O(n).
Amounts up to 10^9 fit in a 32-bit integer, and you only compare them, never add them. The real limit is the order rule: a one-pass swap method in place does not keep arrival order, so plan for an output list.